<?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>Shattered Terminal &#187; memory</title>
	<atom:link href="http://shatteredterminal.com/tag/memory/feed/" rel="self" type="application/rss+xml" />
	<link>http://shatteredterminal.com</link>
	<description>i don't have a tagline yet</description>
	<lastBuildDate>Sun, 11 Apr 2010 18:13:22 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>C++&#8217;s scoped_ptr and unique_ptr smart pointers</title>
		<link>http://shatteredterminal.com/2008/11/scoped_ptr-and-unique_ptr-smart-pointers/</link>
		<comments>http://shatteredterminal.com/2008/11/scoped_ptr-and-unique_ptr-smart-pointers/#comments</comments>
		<pubDate>Sun, 23 Nov 2008 10:43:36 +0000</pubDate>
		<dc:creator>shards</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[boost]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[memory]]></category>

		<guid isPermaLink="false">http://shatteredterminal.com/?p=91</guid>
		<description><![CDATA[I got bitten again just the other day when I was modifying old code. It crashed. Yes, I added an extra delete when one is not required resulting in a double deletion. It reinforced my belief that most pointers in C++ should be smart pointers. A new C++ programmers will be caught often for memory [...]]]></description>
			<content:encoded><![CDATA[<p>I got bitten again just the other day when I was modifying old code. It crashed. Yes, I added an extra delete when one is not required resulting in a double deletion. It reinforced my belief that most pointers in C++ should be smart pointers. A new C++ programmers will be caught often for memory leaks for forgetting to delete a pointer. As you get more experienced, while forgetting to delete becomes far less of a problem, double deletion becomes more rampant (Hey! It&#8217;s hard to keep track of object ownership you know? Especially when you&#8217;re rushing to modify other people&#8217;s code before deadline&#8230;)</p>
<h3>scoped_ptr</h3>
<p>To the rescue is Boost <a href="http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/scoped_ptr.htm"><code>scoped_ptr</code></a> smart pointer. There are two main reasons, in my opinion, to use scoped pointers.</p>
<p>Scoped pointers ease manual memory management. It holds a pointer to the object that it manage and it performs automatic deletion of the object it holds when it is deleted. The scoped_ptr object itself is a templated auto pointer, which means that it will be deleted automatically when it goes out of scope. Here is a simple, incomplete implementation of scoped_ptr:</p>
<pre name="code" class="cpp">template &lt;typename T&gt;
class scoped_ptr : noncopyable {
 public:
  explicit scoped_ptr(T* p = NULL) { p_ = p; }
  ~scoped_ptr() {
    if (p_ != NULL) delete p_;
  }
  void reset(T* p = NULL) {
    if (p_) delete p_;
    p_ = p;
  }

  // Some implementation may choose
  // to crash if p_ is NULL for the
  // following 3 operators.
  T&amp; operator*() const { return *p_; }
  T* operator-&gt;() const { return p_; }
  T* get() const { return p_; }
 private:
  T* p_;
};</pre>
<p>Let&#8217;s analyze the class. It extends Boost&#8217;s <code>noncopyable</code> interface (some would prefer to use macro for this), which implies that a <code>scoped_ptr</code> object may not be copied or assigned to another scoped_ptr. It induces a strict ownership of the owned pointer. As you see above, the destructor of <code>scoped_ptr</code> simply delete the held pointer, similarly with <code>reset(T*)</code> method.</p>
<p>This brings us to a second, more important point. scoped_ptr enforces a strict ownership of an object. In another word, it forces us programmers to think and then rethink about the ownership of an object. Many times, the problem with C++ developers are not forgetting to delete. It is not knowing who exactly owns an object. For example, let&#8217;s check out the following really simple class definition:</p>
<pre name="code" class="cpp">class ConfusedClass {
 public:
  ConfusedClass() {}
  ~ConfusedClass() {}
  void DoSomething() {
     a_ = b_.PerformSomething();
  }
  AnotherClass* GetA() { return a_; }
 private:
  AnotherClass* a_;
  YetAnotherClass b_;
};</pre>
<p>In a world without <code>scoped_ptr</code>, this class can be really confusing. Who owns the object held by <code>a_</code>? Is it <code>b_</code>? Is it <code>ConfusedClass</code>? Or is it the class who calls <code>GetA</code>? The last option looks unlikely here. But it&#8217;s pretty hard to differentiate between the first two cases! A subsequent reader of the class definition would probably need to dig <code>YetAnotherClass</code> to determines that information. (Note also that the destructor is empty, it can be that <code>b_</code> holds the object held by <code>a_</code>, or&#8230; it can be a bug—forgetting to delete <code>a_</code>!)</p>
<p>With <code>scoped_ptr</code>, when we write <code>ConfusedClass</code>, we should be thinking about the ownership of the object held by <code>a_</code>. And if we think this class should owns it, we should use <code>scoped_ptr&lt;AnotherClass&gt; a_</code> instead! That way, subsequent reader of the class definition knows for sure that the object is owned by <code>ConfusedClass</code> (or shall we call it <code>SmartClass</code> now).</p>
<p>As a bonus, code with multiple exit path will be easily managed with <code>scoped_ptr</code> (instead of hunting each exit path and making sure all the pointers that should be deleted are deleted). Imagine how troublesome it is to manage a method with a throw for example. (I remembered writing a Java code where I&#8217;ve had to always have 3 if blocks in the <code>finally</code> part of a <code>try-catch-finally</code>, to actually check for null and close a <code>ResultSet</code>, a <code>PreparedStatement</code>, and an <code>SqlConnection</code>. In C++, I&#8217;ll simply write a wrapper similar to <code>scoped_ptr</code> to perform the closing.)</p>
<h3>unique_ptr</h3>
<p>C++0x expands the smart pointer repertoire even more with <code>unique_ptr</code> (Committee Draft §20.8.12). This smart pointer has a strict ownership as with scoped pointer. However, it is MoveConstructible and MoveAssignable (as described by the CD). What those jargons mean is that a <code>unique_ptr s</code> can be constructed with parameter of another <code>unique_ptr u</code> with a corresponding ownership transfer of the held object from u to s (MoveConstructible) and a <code>unique_ptr u</code> can be assigned to another <code>unique_ptr s</code> with ownership of the owned object transferred from u to s (MoveAssignable).</p>
<p>This pointer adds a little extra value to scoped pointer version. That is, you can transfer ownership (there is no release method in scoped pointer, while <code>unique_ptr</code> has not just a move constructor and move assignment, but also an explicit <code>release</code> method). This is basically a better version of <code>std::auto_ptr</code> (I&#8217;ve heard talk of making auto pointer deprecated).</p>
<p>To effectively used smart pointer, use the correct smart pointer for each of your needs. If you need a strict ownership semantics without any trasnfer, use <code>scoped_ptr</code>. If you need ability to transfer ownership in addition to that, use <code>unique_ptr</code> (or <code>std::auto_ptr</code>). Even better, make such rules part of your software/company&#8217;s style guide. Future maintainers will thank you when he can easily see an orderly semantics in the chaos.</p>
<h3>shared_ptr</h3>
<p>There is another smart pointer introduced in C++0x. The name is <code>shared_ptr</code> (CD &sect; 2.8.13.2). This pointer is basically a referenced-counting smart pointers that implements shared ownership of the held object. When the last <code>shared_ptr</code> holding the particular object is destructed, the object is deleted too. Now, I won&#8217;t delve too much into this smart pointer because I believe in strict ownership as opposed to shared one. There should be a very, very rare situation where it demands shared ownership of an object. In a good software design, only one object should owned a particular object.</p>
<p>Now there is one place where <code>shared_ptr</code> is very, very useful: the STL containers. When you insert or retrieved a member into an STL containers, a copy of the object is made. For performance reason, keeping a pointer in the containers make lots of sense (especially when copying is expensive). As with any pointer usage, it becomes very hard to keep track of these objects. Hence the usage of <code>shared_ptr</code>. Copying a shared pointer is cheap. Additionally, there&#8217;s no risk of forgetting to delete a pointer within an STL containers. (Keep in mind that <code>shared_ptr</code> is usually twice as big as a normal pointer as it needs to keep another pointer to the reference counter.)</p>
<p>Example usage:</p>
<pre name="code" class="cpp">vector&lt;shared_ptr&lt;ClassA&gt; &gt; vector_of_a;
hash_map&lt;int, shared_ptr&lt;ClassA&gt; &gt; map_of_int_to_a;</pre>
]]></content:encoded>
			<wfw:commentRss>http://shatteredterminal.com/2008/11/scoped_ptr-and-unique_ptr-smart-pointers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

