title: Copy-on-write pointer object in C++
body: <p>I tried to follow this article
  <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-on-write" rel="nofollow">http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-on-write</a> on how to implement copy on write pointers in C++. The problem is, it doesn't work for me.</p>
  
  <p>The crux of the object is in overloading the dereference operator (*) to do background copying if it should return a non-const reference:</p>
  
  <pre><code>   const T&amp; operator*() const
      {
          return *m_sp;
      }
      T&amp; operator*()
      {
          detach();
          return *m_sp;
      }
  </code></pre>
  
  <p>Sadly, it seems that only the second version is ever run.
  C-outing the my pointed-to object creates a copy, even doing something like</p>
  
  <pre><code>   CowPtr&lt;string&gt; my_cow_ptr(new string("hello world"));
     const string&amp; const_ref=*my_cow_ptr; 
  </code></pre>
  
  <p>causes the <code>detach()</code> function to run.  </p>
  
  <p>Any ideas on why it's not working as advertised?</p>