<?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++11</title>
	<atom:link href="https://timoch.com/blog/tag/c11/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>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-69d57b0c7e25b049510886/] 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>
