    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: auto_ptr || !auto_ptr</title>
        <link>https://members.accu.org/index.php/articles/1456</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #17/18 - Jan 1997</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c228/">1718</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-228/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+228/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;auto_ptr || !auto_ptr</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 31 January 1997 08:53:00 +00:00 or Fri, 31 January 1997 08:53:00 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<p> This article takes a sideways glimpse at the auto_ptr
class from the standard C++ library. It does this by considering the
forces that shaped auto_ptr, and implements a class that seems to
resolve those forces sensibly. However, the re&shy;sulting class turns
out to be very different to auto_ptr. Why is this? In all honesty I
have to say that I feel it's because auto_ptr has lost its way and has
turned into something of a dog's breakfast.</p>
<p> The basic thing to remember with auto_ptr is that it is
supposed to improve the safety of handling of dynamically allocated
objects within block structured code. What does that mean? Let's look
at an example...</p>
<pre>file_spy* smiley = new file_spy(top_secret);<br>smiley-&gt;espionage();</pre>
<p> The problem with this code is that espionage() may throw
an exception. If it does then the stack will unwind past smiley and we
will have a memory leak. An answer to this problem is well known. You
create a class whose destruc&shy;tor deletes the dynamically allocated
object [<a href="#1">1</a>]. For example...</p>
<pre>template&lt;typename type&gt;<br>class owner {<br>public:<br>  owner( type* acquire )<br>  : resource(acquire) {}<br>  ~owner() { delete resource; )  <br>public: // query<br>  type* get() const { return resource; }<br>  type* operator-&gt;() const<br>  { return resource; }<br>  type&amp; operator*() const<br>  { return *resource; }  <br>private: // state<br>  type* resource;<br>};<br></pre>
<p>Now the example can be re-written as...</p>
<pre>owner&lt;file_spy&gt;<br>    smiley( new file_spy(top_secret) );<br>...<br>smiley-&gt;espionage();<br></pre>
<p>...and if espionage() throws an exception, the owner
destructor will delete the dynamic file_spy, thus plugging the memory
leak. The interesting part is when you try to flesh out owner, to
make it &quot;minimal but complete&quot;. The most obvious missing parts
are the copy constructor and the assignment operator. The usual
signatures for these are...</p>
<pre>owner( const owner&amp; rhs );<br>owner&amp; operator=( const owner&amp; rhs );</pre>
<p> The problem with these two is the presence of the const
in both signatures. Suppose you write the copy constructor like this...</p>
<pre>owner( const owner&amp; rhs )<br> &nbsp;  : resource(rhs.resource) {)</pre>
<p> You now have two pointers pointing at one dy&shy; namically
allocated object. This is a sure fire way to create a dangling pointer.
For exam&shy;ple...</p>
<pre>void dangle( owner&lt;snafu&gt; fubar )<br>{<br>  ...<br>}<br><br>owner&lt;snafu&gt; oops(new snafu(1,2));  <br>dangle(oops);</pre>
<p>Here dangle will copy construct the fubar pa&shy;rameter from
oops, and when dangle returns it will call the destructor for the copy
constructed fubar parameter, thus deleting the snafu pointed to
by oops. When oops goes out of scope it too will have its destructor
called and it too will try to delete the object already deleted by the
dangle parameter. How can you solve this problem? One way is to keep a
count of how many owners are pointing to the resource. This is
reference counting. However, owner takes a different approach. Instead
owner en&shy;sures that a dynamically allocated object is only ever
pointed to by one owner. In other words if you write this...</p>
<pre>snafu* p = new snafu(l,2);  <br>owner&lt;snafu&gt; alpha(p);
owner&lt;snafu&gt; beta(alpha);</pre>
<p> Then owner has to ensure that either alpha or beta ends
up owning p, but not both. Given this it might seem logical to
implement the copy constructor like this...</p>
<pre>owner( const owner&amp; rhs ) <br>{<br>  type* ptr = rhs.resource;<br>  rhs.resource = 0;<br>  resource = ptr;<br>}<br></pre>
<p>The idea here is that rhs passes the resource on to the
newly constructed object. This won't work. The problem is that rhs is
declared const, so the compiler will not allow the line...</p>
<pre>rhs.resource = 0;<br></pre>
<p>For this reason, suppose you give non-const references to the
copy constructor and the as&shy; signment operator...</p>
<pre>owner( owner&amp; rhs)<br>{<br>  type* ptr = rhs.resource;<br>  rhs.resource =0;<br>  resource = ptr;<br>}<br><br>owner&amp; operator=(owner&amp; rhs )<br>{<br>  if (resource != 0)<br>    delete resource;<br>  type* ptr = rhs.resource;<br>  rhs.resource = 0;<br>  resource = ptr;<br>  return *this;<br>}<br></pre>
<p>This solves the problem, but up pops another (an ominous
sign). The apparently legal code...</p>
<pre>owner&lt;snafu&gt; f();           // function returning<br>                            // owner&lt;snafu&gt;<br>owner&lt;snafu&gt; delta( f() );  // copy <br>                            // constructor</pre>
<p>...fails to compile. It fails because the copy constructor argument
is an unnamed tempo&shy;rary object returned by
f() and the C++ stan&shy;dard states that temporary objects cannot be
bound to non-const reference parameters [<a href="#2">2</a>]. Okay I
hear you say,
that's easy to work round, make the parameter a named non-temporary
object like this...</p>
<pre>owner&lt;snafu&gt; tmp;<br>tmp = f();<br>owner&lt;snafu&gt; delta(tmp);</pre>
<p>This won't work either. The reason is that the assignment is really
just syntactic sugar for...</p>
<pre>tmp.operator=( f() );</pre>
<p> and, once again, the parameter is an unnamed temporary. So,
giving a non-const reference to the copy constructor and
assignment operator of owner has had a surprising result. It has made
it impossible to return an owner object from a function by value. At
this point I hope you feel owner is losing its way. It seems to be
lurching from one problem to another, and the hack-work-rounds are
simply making matters worse. Time to take a step back and start to
think again. Remember that the original moti&shy;vation was to improve
the exception safety of dynamically allocated objects in block
struc&shy;tured code. In this light, passing an owner ob&shy;ject
around as the return value from a function (or by value into a
function) can be seen as an attempt to misuse owner. A
reasonable approach is therefore to revoke the copy con&shy;
structor and the assignment operator completely. One way to do this is
to inherit the inability [<a href="#3">3</a>] to copy...</p>
<pre>class no_copy<br>{<br>public:<br>  no_copy() {} <br>private:<br>  //NO definition for these<br>  no_copy( const no_copy&amp; );<br>  no_copy&amp; operator=( const no_copy&amp; );<br>};<br><br>template&lt;typename type&gt;<br>class owner : private no_copy<br>{<br>  ...<br>};<br><br></pre>
<p>What else needs doing to make owner more complete? Well, it
seems unreasonable not to provide a default constructor. The
easiest way to do this is to provide a default value to the
constructor. It also seems reasonable to provide methods to explicitly
control ownership.</p>
<pre>template&lt;typename type&gt;  <br>class owner : private no_copy<br>{<br>public: // construction/destruction <br>  explicit owner( type* acquire=0 )<br>    : resource(acquire) {} <br>  ~owner() ( delete resource; }<br><br>public: // query<br>  type&amp; operator*() const<br>  { return *resource; }<br>  type* operator-&gt;() const<br>  { return resource; }<br>  type* get() const { return resource; }  <br><br>public: // services<br>  void transfer( owner&lt;type&gt;&amp; a )<br>  {<br>    reset(a.release());<br>  }<br></pre>
<pre>  void swap( owner&lt;type&gt;&amp; a )<br>  {<br>  &nbsp; ::swap(resource, a.resource);<br>  }<br><br>  void reset( type* ptr=0 )<br>  {<br>    delete resource; <br>    resource = ptr; <br>  }<br><br>  type* release()<br>  {<br>    type* ptr = resource; <br>    resource = 0;  <br>    return ptr;<br>  }<br><br>private: // state  <br>  type* resource;<br>};<br></pre>
<p>Finally let's see a small example of owner in use.
Suppose we have a design where a pub&shy;lisher object is responsible
for notifying all registered subscriber objects when a resource changes
[<a href="#4">4</a>]. Further, suppose that the sub&shy;scriber objects
need only retain
a single copy of the most up to date resource.</p>
<pre>class subscriber <br>{<br>public: <br>  //...<br>  void notify(  const resource&amp; update  ) <br>  {<br>    // possible multi-thread lock here  <br>    latest.reset( new resource(update) );<br>  }<br>  //...<br>private:<br>  owner&lt;resource&gt; latest;<br>};<br></pre>
<p> [<a name="1"></a>1] The C++ Language. 2<sup>nd</sup> edition,
Bjarne Stroustrup, Addison Wesley, ISBN 0-201-53992-6,
9.4 Resource Acquisition p308</p>
<p>also</p>
<p> The Design and Evolution of C++, Bjarne Stroustrup,
Addison Wesley, ISBN 0-201-54330-3, 16.5 Resource Management p388</p>
<p> [<a name="2"></a>2] Many C++ compilers do not implement this yet.</p>
<p> [<a name="3"></a>3] You can inherit inability as well as ability.
For example you can inherit the inability to
distinguish certain colours. It's called colour blindness.</p>
<p> [<a name="4"></a>4] Design Patterns, Gamma et al, Addison Wesley,
ISBN 9-201-63361-2, Observer p293</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
