<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TiMoch &#187; c++</title>
	<atom:link href="https://timoch.com/blog/tag/c-plus-plus/feed/" rel="self" type="application/rss+xml" />
	<link>https://timoch.com/blog</link>
	<description>on edge</description>
	<lastBuildDate>Tue, 29 Apr 2014 15:02:50 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=3.9.40</generator>
	<item>
		<title>std::unique_ptr semantics</title>
		<link>https://timoch.com/blog/2013/04/std-unique_ptr-semantic/</link>
		<comments>https://timoch.com/blog/2013/04/std-unique_ptr-semantic/#comments</comments>
		<pubDate>Sat, 13 Apr 2013 17:33:22 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[unique_ptr]]></category>

		<guid isPermaLink="false">http://www.timoch.com/blog/?p=180</guid>
		<description><![CDATA[Probably the best feature introduced by C++11 is std::unique_ptr. It will automagically make sure your dynamically allocated objects are deleted when you don&#8217;t use them anymore. In previous versions of C++, you needed to rely exclusively on documentation and conventions to ensure dynamically allocated memory was handled properly. With C++11, you can ask the compiler [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Probably the best feature introduced by C++11 is std::unique_ptr. It will automagically make sure your dynamically allocated objects are deleted when you don&#8217;t use them anymore.</p>
<p>In previous versions of C++, you needed to rely exclusively on documentation and conventions to ensure dynamically allocated memory was handled properly. With C++11, you can ask the compiler to help you out and enforce ownership semantics. Take the following code for example, you need to ensure you call delete when you are done with the object created by function factory(). The compiler will not complain if you forget and you end up with a memory leak.</p><pre class="crayon-plain-tag">struct A { int field; };
A* factory() { return new A(); }
void useFactory() {
    A* ptr = factory();
    std::cout &lt;&lt; ptr-&gt;field &lt;&lt; std::endl;
    // you must remember to call delete
    delete ptr;
}</pre><p></p>
<h3>What can std::unique_ptr do for you ?</h3>
<p>With std::unique_ptr, you cannot casually forget to delete the pointer. std::unique_ptr owns the allocated object unless this ownership is explicitly transferred to another entity (eg. another unique_ptr, a std::shared_ptr). When a std::unique_ptr goes out of scope, it will delete any object it owns.</p><pre class="crayon-plain-tag">struct A { int field; };
std::unique_ptr&lt;A&gt; factory() { return std::unique_ptr&lt;A&gt;(new A()); }
void useFactory() {
    std::unique_ptr&lt;A&gt; ptr = factory();
    std::cout &lt;&lt; ptr-&gt;field &lt;&lt; std::endl;
    // ptr will delete allocated A automatically 
}</pre><p>The most explicit way of transferring ownership is via function std::move(). Using the same above example, we can see how it works.</p><pre class="crayon-plain-tag">struct A { int field; };
std::unique_ptr&lt;A&gt; factory() { return std::unique_ptr&lt;A&gt;(new A()); }
void useFactory() {
    std::unique_ptr&lt;A&gt; ptr1 = factory(); 
    std::unique_ptr&lt;A&gt; ptr2 = std::move(ptr1);
    // now ptr2 owns the instance of A 
    // and ptr1 is holding a null pointer
}</pre><p>You cannot directly assign an instance of std::unique_ptr to another. This rule ensures that no two unique_ptr can claim ownership of the same dynamically allocated object. It prevents deleting an object multiple times.<br />
This is the magic of std::unique_ptr, you always know who owns the pointed value. By consistently using unique_ptr, you know at a glance when you own a heap object and when you yield ownership to another. Moreover, this rule is enforced by the compiler &#8212; the less you need to worry about, the better.</p>
<h3>How do you use std::unique_ptr ?</h3>
<p>std::unique_ptr helps you express your intent with regards to ownership transfer. Transfer of ownership occurs in the following general cases :</p>
<ul>
<li>Returning a dynamically allocated object from a function</li>
<li>Passing a such an object to a function</li>
</ul>
<h4>Returning a std::unique_ptr</h4>
<p>Returning a heap-allocated object from a function requires that the caller delete it when it is done with.</p>
<p>By returning a unique_ptr, you ensure the caller takes ownership of the pointed object. In the example below, the signature of createVector() ensures the caller takes the responsibility for releasing the created vector. Normal flow of execution guarantees memory will be released whenever the returned unique_ptr is destroyed.</p><pre class="crayon-plain-tag">typedef std::vector&lt;int&gt; Vector;
std::unique_ptr&lt;Vector&gt; createVector() { 
    return std::unique_ptr&lt;Vector&gt;(new Vector()); 
}

void caller() {
    std::unique_ptr&lt;Vector&gt; ptr = factory();
    // use the returned vector

    // nothing needs to be done here
    // the Vector will be deleted
}</pre><p></p>
<h4>Passing a std::unique_ptr to a function</h4>
<p>A function taking a unique_ptr takes definitive ownership of the pointed object. The caller will not even have the ability to access the pointed object after the function call.<br />
Notice the call to function std::move(), it is required and helps you actually see that ownership is transferred to the function.</p><pre class="crayon-plain-tag">void takePtr(std::unique_ptr&lt;int&gt; ptr) { /* ... */ }

void caller() {
    std::unique_ptr&lt;int&gt; ptr = new int(5);
    // explicitly transfer ownership with std::move
    takePtr(std::move(ptr));
    // now ptr holds a null pointer. takePtr() has effectively taken ownership.

    // a temporary (rvalue reference) is implicitly moved 
    takePtr(std::unique_ptr&lt;int&gt;(new int(6)));
}</pre><p></p>
<h4>Passing a const reference to a unique_ptr</h4>
<p>The called function can use the pointed object but may not interfere with its lifetime. The caller function keeps ownership of the pointed object.</p>
<p>In my opinion, there is no real benefit to using a const reference to a unique_ptr from simply using a raw pointer to the object. On the contrary, it introduces a constraint on the caller that it must manage the pointed object through a unique_ptr. But what if your caller context requires you have shared ownership (std::shared_ptr)? Since we mostly care about whether ownership is transfered (not how ownership is cared for), a raw pointer is perfect.</p><pre class="crayon-plain-tag">void useUniquePtr(const std::unique_ptr&lt;int&gt; &amp; ptr) { /* ... */ }
void useRawPtr(int * ptr) { /* ... */ }

void caller() {
    std::unique_ptr&lt;int&gt; ptr = new int(5);
    // useUniquePtr() can use but does not own the pointed object
    useUniquePtr(ptr);
    // same semantics
    useRawPtr(ptr.get());
}</pre><p></p>
<h4>Passing a non-const reference to a unique_ptr</h4>
<p>This is, in my opinion, the most complex situation. The called function may or may not take ownership of the passed pointer. &#8220;may or may not&#8221; is really part of the functions contract. If the called function uses std::move() on the passed unique_ptr, it effectively takes onwnership and once it gives control back to the caller, the caller does not own the pointer anymore, it doesn&#8217;t even know the value of the pointer anymore. On the other hand, if the callee merely uses the provided pointer without moving it, the caller still owns the pointed object.</p><pre class="crayon-plain-tag">void useUniquePtr(std::unique_ptr&lt;int&gt; &amp; ptr) { /* ... */ }

void caller() {
    std::unique_ptr&lt;int&gt; ptr = new int(5);
    useUniquePtr(ptr);
    // if useUniquePtr() used std::move() on ptr, it took ownership 
    // of the pointed int, so ptr is now holding a nullptr
    // otherwise it still owns the int and will delete it when the 
    // current scope ends
    if (ptr.get() == nullptr)
        std::cout &lt;&lt; "ptr has been moved away" &lt;&lt; std::endl;
    else
        std::cout &lt;&lt; "ptr is still ours" &lt;&lt; std::endl;
}</pre><p></p>
<h3>Conclusion</h3>
<p>C++11 provides us with a great tool for managing the lifetime of dynamically allocated object. When used consistently, std::unique_ptr lets your code really express when ownership of a dynamic object is transferred and in which direction directly. The compiler will even see that the semantics are respected <strong>at compile-time</strong>.</p>
<p>However, they are of no use when you don&#8217;t intend to express ownership semantics. Pass raw pointers whenever you can but make sure that you use std::unique_ptr or another similar smart pointer when you mean to transfer ownership.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/04/std-unique_ptr-semantic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>boost::serialization coupling issue</title>
		<link>https://timoch.com/blog/2013/04/boost-serialization-coupling-issue/</link>
		<comments>https://timoch.com/blog/2013/04/boost-serialization-coupling-issue/#comments</comments>
		<pubDate>Fri, 12 Apr 2013 15:00:45 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://www.timoch.com/blog/?p=159</guid>
		<description><![CDATA[I was evaluating boost::serialization today. Based on the design goals mentioned in the library&#8217;s introduction, I felt like boost::serialization would suit my needs. An interesting point is this : 8. Orthogonal specification of class serialization and archive format. That is, any file format should be able to store serialization of any arbitrary set of C++ [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I was evaluating boost::serialization today. Based on the design goals mentioned in the library&#8217;s <a href="http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html" target="_blank">introduction</a>, I felt like <span class="codecolorer me1">boost::serialization</span> would suit my needs.</p>
<p>An interesting point is this :</p>
<p><em>8. Orthogonal specification of class serialization and archive format. That is, any file format should be able to store serialization of any arbitrary set of C++ data structures without having to alter the serialization of any class.</em></p>
<p>At first, I interpreted it as an intent to decouple the serialization code (that knows about the object&#8217;s internals) and the archive format.<br />
Consider this:</p><pre class="crayon-plain-tag">struct ClassA {
    ...
    template &lt;typename Archive&gt;
    void serialize(Archive ar, unsigned int version) {
        ar &amp; member1_;
        ar &amp; member2_;
        ...
        ar &amp; membern_;
    }
    ...
}</pre><p>All is fine, ClassA does not know the specifics of type Archive. Any object implementing the Archive concept will do just fine.</p>
<p>Yet, I have a problem with this. Inline code in headers has a tendency to irritate me. It hides the structure of the classes you implement so I often use the PImpl idiom.<br />
I want to (or must in the case of PImpl) move the implementation to ClassA.cpp.<br />
But &#8230; can I ?</p>
<p>serialize() is a template method. Can I forward declare a template method ? Well, yes.</p>
<p>In ClassA.hpp :</p><pre class="crayon-plain-tag">struct ClassA {
    ...
    template &lt;typename Archive&gt;
    void serialize(Archive &amp; ar, unsigned int version);
    ...
}</pre><p>In ClassA.cpp:</p><pre class="crayon-plain-tag">template &lt;typename Archive&gt;
void serialize(Archive &amp; ar, unsigned int version) {
    ar &amp; member1_;
    ar &amp; member2_;
    ...
    ar &amp; membern_;
}</pre><p>In main.cpp, try to serialize an instance of ClassA :</p><pre class="crayon-plain-tag">#include "ClassA.hpp"
#include &lt;boost/archive/text_oarchive.hpp&gt;
#include &lt;boost/archive/text_iarchive.hpp&gt;
#include &lt;fstream&gt;

int main(int argc, char ** argv) {
  ClassA a;

  std::ofstream ofs("output.txt");
  boost::archive::text_oarchive oa(ofs);
  oa &lt;&lt; a;

  return 0;
}</pre><p>Compile and link :</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">g++ -c main.cpp -o main.o<br />
g++ -c ClassA.cpp -o ClassA.o<br />
g++ main.o -lboost_serialization -o program<br />
main.o: In function &lt;code&gt;void boost::serialization::access::serialize&amp;lt;boost::archive::text_oarchive, classa=&quot;&quot;&amp;gt;(boost::archive::text_oarchive&amp;amp;, ClassA&amp;amp;, unsigned int)':<br />
main.cpp:(.text._ZN5boost13serialization6access9serializeINS_7archive13text_oarchiveE6ClassAEEvRT_RT0_j[_ZN5boost13serialization6access9serializeINS_7archive13text_oarchiveE6ClassAEEvRT_RT0_j]+0x25): undefined reference to</div></td></tr></tbody></table></div>
<p>void ClassA::serialize&lt;boost::archive::text_oarchive&gt;(boost::archive::text_oarchive&amp;, unsigned int)&#8217;<br />
collect2: error: ld returned 1 exit status<br />
make: *** [program] Error 1</code><br />
Does this compile ? Yes. Does this link ? &#8230; No!</p>
<p>What&#8217;s the compiler trying to tell me ? Undefined reference to ClassA::serialize(&#8230;). But I defined it, no ?<br />
Well, yes and no. You wrote the code but it is a template function. So it needs to be instantiated at compile-time. When main.cpp is compiled, it sees the forward-declaration of ClassA::serialize() and assumes that the linker will find the implementation of void ClassA::serialize&lt;boost::archive::text_oarchive&gt;(boost::archive::text_oarchive&amp;, unsigned int) somewhere.<br />
But it does not because, ClassA.cpp while implementing the template function does not instantiate it. ClassA::serialize() is parsed but never compiled into actual machine code.</p>
<p>You can check for yourself. Look at the file size :</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">-rw-rw-r-- 1 timoch timoch 940 Apr 12 12:59 ClassA.o<br />
-rw-rw-r-- 1 timoch timoch 143088 Apr 12 12:59 main.o</div></td></tr></tbody></table></div>
<p>940 bytes ? That&#8217;s not a lot.</p>
<p>You can force the instantiation of ClassA::serialize() in ClassA.cpp. Add the following at the end:</p><pre class="crayon-plain-tag">#include
template void ClassA::serialize(boost::archive::text_oarchive &amp;, unsigned int);</pre><p>It works, but is it good ? Not to me.</p>
<p>I need to include a header defining the implementation of the specific format I serialize to. I also need to include text_iarchive.hpp for the loading process to work. Tomorrow, when my object needs to be serialized to another format as part as another use case, I will need to modify its implementation file to include the specifics of that other format. I will need to do this for each and every class to be serialized &#8230; not something I would enjoy.</p>
<p>&nbsp;</p>
<h4>Conclusion</h4>
<p>&nbsp;</p>
<p>Templates provide a huge flexibility. Here it is used to enable the &amp; operator to serve as both an extract and inject operator. However, it is at the expense of forcing the client application to put the saving/loading implementation in the same compile unit as the definitions of your target format. It completely voids the efforts put toward decoupling the serialized objects and the format they serialize to.</p>
<p>There are ways to achieve the same flexibility of &#8216;same operator&#8217; saving and loading while preserving decoupling with the serialization format. I will come back to that in a later post.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/04/boost-serialization-coupling-issue/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get confused by VC++</title>
		<link>https://timoch.com/blog/2013/03/how-to-get-confused-by-vc/</link>
		<comments>https://timoch.com/blog/2013/03/how-to-get-confused-by-vc/#comments</comments>
		<pubDate>Wed, 27 Mar 2013 14:17:34 +0000</pubDate>
		<dc:creator><![CDATA[timoch]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[vc++]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.timoch.com/blog/?p=131</guid>
		<description><![CDATA[Today, I came across a confusing compilation error with MS VC++ using a std::unique_ptr with a custom deleter. Here the code snippet: [crayon-69e595fc97b1e198621656/] The compiler complains : 12345678910111213c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2218): error C2338: unique_ptr constructed with null deleter pointer 1&#62; c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2214) : while compiling class template member function [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Today, I came across a confusing compilation error with MS VC++ using a <em>std::unique_ptr</em> with a custom deleter.</p>
<p>Here the code snippet:</p>
<p></p><pre class="crayon-plain-tag">#include &lt;memory&gt;
#include &lt;string&gt;

typedef void (*void_delete)(void *);

template&lt;typename T&gt;
void void_deleter(void * ptr) { delete reinterpret_cast&lt;T*&gt;(ptr); }

std::unique_ptr&lt;void, void_delete&gt; f1() {
return std::unique_ptr&lt;void, void_delete&gt;(new std::string("haha"), void_deleter);
}
std::unique_ptr&lt;void, void_delete&gt; f2() {
return std::unique_ptr&lt;void, void_delete&gt;(nullptr);
}</pre><p> </p>
<p>The compiler complains :</p>
<div class="codecolorer-container text dawn" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2218): error C2338: unique_ptr constructed with null deleter pointer<br />
1&gt; c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2214) : while compiling class template member function 'std::unique_ptr::unique_ptr(std::nullptr_t)'<br />
1&gt; with<br />
1&gt; [<br />
1&gt; _Ty=void,<br />
1&gt; _Dx=void_delete<br />
1&gt; ]<br />
1&gt; c:\sources\source1.cpp(9) : see reference to class template instantiation 'std::unique_ptr' being compiled<br />
1&gt; with<br />
1&gt; [<br />
1&gt; _Ty=void,<br />
1&gt; _Dx=void_delete<br />
1&gt; ]</div></td></tr></tbody></table></div>
<p>The gotcha is that the compiler complains of a <em>reference to class template instantiation</em> on line 9. This is the definition of f1(). </p>
<p>However, the actual issue is on line 13 in the implementation of f2(). A <em>std::unique_ptr</em> is instantiated with a nullptr and no deleter. The nullptr constructor has a <em>static_assert</em> that protects from uninitialized function-pointer deleter. I wonder what could go wrong with an uninitialized function pointer &#8230; <img src="https://timoch.com/blog/wp-includes/images/smilies/icon_neutral.gif" alt=":-|" class="wp-smiley" /> </p>
<p>The compiler gives you the line of the first appearance of <em>std::unique_ptr</em> in the compilation unit not the actual line that causes the error &#8230; Easy enough to spot on a trimmed down example like this one. It tooks me quite some time to find in a code file with several hundred lines of code and many changes at once.</p>
]]></content:encoded>
			<wfw:commentRss>https://timoch.com/blog/2013/03/how-to-get-confused-by-vc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
