    <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  :: Uncounted pointers in C++</title>
        <link>https://members.accu.org/index.php/journals/518</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>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #34 - Oct 1999 + Programming Topics</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/journals/">All</a>

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c170/">34</a>
                    (11)
<br />

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

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

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

                                            <a href="https://members.accu.org/index.php/journals/c170-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c170+65/">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;Uncounted pointers in C++</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 October 1999 17:50:55 +01:00 or Tue, 26 October 1999 17:50:55 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>Sometimes I come across an idea that strikes me as &quot;interesting,
but is there really a use for it&quot;. Less frequently, I subsequently
find so many uses for it that I can't imagine how I ever survived
without. I first encountered the idea of 'weak references' in
discussions of Java garbage collection. Since then I've found
several applications for the idea in C++.</p>
<p>The idea of a reference is much more general than the C++
language element of the same name. The broader definition used in
design, garbage collection, and other programming languages
includes any mechanism for referring to an object. In C++ this
would include pointers (both base types and the various types of
'smart pointer'). It is this more general definition that I use in
this article.</p>
<p>Garbage Collection is a tool for managing the memory referred to
by references - it works on the principle that when there are no
active references to an object then the program can never use the
object again and the memory allocated to it may be reclaimed. This
works well in languages like Java that have support for references
in the language. (In Java all objects are managed by
references.)</p>
<p>Not all references need be equal, and two of the variations that
have been developed are 'strong references' and 'weak references'.
The garbage collection tool only considers strong references when
deciding if an object may be collected. Any weak references to an
object will become null if the object is collected.</p>
<p>There are other variations, for example, in Java there are now
three reference classes WeakReference, SoftReference and
PhantomReference. These are essentially hooks into the Java garbage
collection mechanism with different collection semantics.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id="d0e30"></a>smart
pointers</h2>
</div>
<p>For a variety of reasons garbage collection is not standard in
C++ and in its most general form would be impractical to implement.
For instance, C++ allows one to encrypt a pointer (e.g. by xoring
it with a password), to write it out to a file, destroy all trace
of the original, reload the encrypted version, decrypt it and
regain access to the original object.</p>
<p>Instead of garbage collection C++ programs use a variety of
memory management techniques. One of the most effective of these is
the use of a smart pointer - classes that emulate a pointer and
know when an object is to be delete. The standard library contains
only one design of smart pointer - the auto_ptr template but there
are many other possibilities. (For some of the possibilities check
out <a href="http://www.boost.org/" target=
"_top">http://www.boost.org/</a> and arglib on my website at
<a href="http://www.octopull.demon.co.uk/" target=
"_top">http://www.octopull.demon.co.uk/</a>.)</p>
<p>The idea of strong and weak references inspired the counted_ptr
and uncounted_ptr templates in my arglib library. (We'll deal with
uncounted_ptr shortly, after discussing counted_ptr.)</p>
<p>The strong reference implementation is counted_ptr and works by
keeping count of the number of references to an object so that it
may be deleted when the count reaches zero. (There is another
implementation of this same idea on the boost website as
shared_ptr.)</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e47" id="d0e47"></a>The problem
with <tt class="classname">counted_ptr</tt></h2>
</div>
<p>As proponents of garbage collection will be quick to point out -
there are some problems with this form of reference counting. If
you've used a version of <tt class="classname">counted_ptr</tt> or
any other kind of reference counting pointer then you will know the
main issue is that of loops.</p>
<p>A loop occurs when two (or more) objects - such as &quot;Pippa&quot; and
&quot;Alan&quot; in Example 1 - contain a cycle of references to each other.
In the example Pippa is never deleted because of the reference in
Alan, but Alan is never deleted because of the reference in
Pippa.</p>
<p>Two other things you will notice in the example are parts of a
test harness framework: the macro ARG_TEST and the class <tt class=
"classname">instance_count</tt>. ARG_TEST logs successful tests or
reports unsuccessful ones, instance_count is a utility class that
counts the instances in existence.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e64" id="d0e64"></a>Example 1</h3>
</div>
<pre class="programlisting">
class man;


class woman
{
public:
  void set_husband(counted_ptr&lt;man&gt; value);
private:
  counted_ptr&lt;man&gt; husband;
  instance_count   t;
};


class man
{
public:
  void set_wife(counted_ptr&lt;woman&gt; value);
private:
  counted_ptr&lt;woman&gt; wife;
  instance_count     t;
};


void woman::set_husband(counted_ptr&lt;man&gt;value)
  { husband = value; }
void man::set_wife(counted_ptr&lt;woman&gt; value)
  { wife = value; }


void f()
{
  {
    counted_ptr&lt;woman&gt; pippa(new woman);
    ARG_TEST(1 == instance_count::instances);
    {
      counted_ptr&lt;man&gt; alan(new man); 
      ARG_TEST(2==instance_count::instances);

      alan-&gt;set_wife(pippa);
      pippa-&gt;set_husband(alan);
    }
    ARG_TEST(2 == instance_count::instances);
  }

  // &quot;Look ma - I've leaked!&quot;
  ARG_TEST(2 == instance_count::instances);
}
</pre>
<p>Before encountering the idea of weak references and developing
explicit support for them I used a mix of smart and raw pointers
(with an often arbitrary choice of direction for the ownership).
However, as Example 2 illustrates, this leads to the need for Pippa
(say) to notify Alan that she's being deleted.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e71" id="d0e71"></a>Example 2</h3>
</div>
<pre class="programlisting">
class man;


class woman
{
public:
  void set_husband(counted_ptr&lt;man&gt; value);
  ~woman();
private:
  counted_ptr&lt;man&gt; husband;
  instance_count   t;
};


class man
{
public:
  man();
  void set_wife(woman* value);
private:
  woman*         wife;
  instance_count t;
};


void woman::set_husband(counted_ptr&lt;man&gt;value) 
{ husband = value; }

woman::~woman()
{ if (husband.get()) husband-&gt;set_wife(0); }

man::man()
  : wife(), t()
{}

void man::set_wife(woman* value)
{ wife = value; }


void f()
{
  {
    counted_ptr&lt;woman&gt; pippa(new woman);
    ARG_TEST(1 == instance_count::instances);
    {
      counted_ptr&lt;man&gt; alan(new man); 
      ARG_TEST(2== instance_count::instances);

      alan-&gt;set_wife(pippa.get());
      pippa-&gt;set_husband(alan);
    }
    ARG_TEST(2 == instance_count::instances);
  }
  ARG_TEST(0 == instance_count::instances);
}
</pre>
<p>Even in our simple example this is ugly. In more general usage
this can lead to a need to maintain a list of objects to notify and
the complexity of maintaining it. Other designs, such as external
association lists may be more manageable, but this is still a far
cry from the effortlessness we might expect from smart
pointers.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e78" id=
"d0e78"></a>uncounted_ptr</h2>
</div>
<p>An <tt class="classname">uncounted_ptr</tt> refers to the same
object as a <tt class="classname">counted_ptr</tt> but isn't
included in the reference count. This makes it the weak reference
type corresponding to <tt class="classname">counted_ptr</tt>'s
strong reference. When the object is deleted (because there are no
more <tt class="classname">counted_ptr</tt>s referring to it) the
<tt class="classname">uncounted_ptr</tt> becomes zero.</p>
<p>With <tt class="classname">uncounted_ptr</tt> in our toolkit we
can now revisit the example. The loop problem is solvable by
changing the link implementation between 'man' and 'woman' to
<tt class="classname">uncounted_ptr</tt>. This breaks the loop by
allowing Pippa to be deleted in Example 3. The example also
illustrates that there is no dangling reference left in Alan - an
ever-present danger when using raw pointers.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e106" id="d0e106"></a>Example 3</h3>
</div>
<pre class="programlisting">
class man;


class woman
{
public:
  void set_husband(uncounted_ptr&lt;man&gt; value);
private:
  uncounted_ptr&lt;man&gt; husband;
  instance_count t;
};


class man
{
public:
  void set_wife(uncounted_ptr&lt;woman&gt; value);
private:
  uncounted_ptr&lt;woman&gt; wife;
  instance_count t;
};


void woman::set_husband(uncounted_ptr&lt;man&gt;value)
{ husband = value; }

void man::set_wife(uncounted_ptr&lt;woman&gt; value)
{ wife = value; }


void f()
{
  {
    counted_ptr&lt;woman&gt; pippa(new woman);
    ARG_TEST(1 == instance_count::instances);
    {
      counted_ptr&lt;man&gt; alan(new man); 
      ARG_TEST(2== instance_count::instances);

      alan-&gt;set_wife(pippa);
      pippa-&gt;set_husband(alan);
    }
// alan has gone, but no need to inform pippa
    ARG_TEST(1 == instance_count::instances);
  }
  ARG_TEST(0 == instance_count::instances);
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e111" id="d0e111"></a>using smart
pointers</h2>
</div>
<p>There are a few points to note about any smart pointers you may
be using. Most importantly, you need to understand the ownership
regime that they implement. Most smart pointers, like the standard
<tt class="classname">auto_ptr</tt>, take ownership of an object,
so initialising two <tt class="classname">auto_ptr</tt>s from a
single raw pointer value will lead to problems. (Because both
pointers are entitled to delete the object, but this will lead to
undefined behavior.)</p>
<p>Like <tt class="classname">auto_ptr</tt>, <tt class=
"classname">counted_ptr</tt> assumes ownership of the referenced
object. Unlike <tt class="classname">auto_ptr</tt> it shares (not
transfers) the ownership by means of the copy construction
assignment operations. This gives <tt class=
"classname">counted_ptr</tt> the required value semantics needed to
be used successfully in standard library containers.</p>
<p>The <tt class="classname">uncounted_ptr</tt> template refers to
an object owned by one or more <tt class=
"classname">counted_ptr</tt>s, but it does not share in the
ownership of the object. An <tt class=
"classname">uncounted_ptr</tt> automatically becomes 0 when the
object is deleted. (Note however, that dereferencing an <tt class=
"classname">uncounted_ptr</tt> implicitly creates a temporary
<tt class="classname">counted_ptr</tt> preserving the object long
enough to complete the current expression.)</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e153" id="d0e153"></a>counted_ptr
interface</h3>
</div>
<pre class="programlisting">
template&lt;typename pointee_type&gt;
class counted_ptr : public  specialised_counted_ptr_base&lt;pointee_type&gt;
{
  typedef specialised_counted_ptr_base&lt;pointee_type&gt; base_type;

public:
  /** Construction */
  counted_ptr() ; /// &quot;0 initialised&quot; pointer
  explicit counted_ptr(pointee_type* p); /// Takes ownership of p
  counted_ptr(const counted_ptr&amp; rhs); /// Take value of rhs
  template&lt;typename rhs_pointee_type&gt;
  counted_ptr(const specialised_counted_ptr_base&lt;rhs_pointee_type&gt;&amp; rhs); /// Take value of rhs
  ~counted_ptr() throw();

  /** Accessors */
  pointee_type* get() const; /// Returns contents
  pointee_type* operator-&gt;() const; /// Dereference op
  pointee_type&amp; operator*() const; ///  Dereference op

  /** Mutators */
  counted_ptr&amp; operator=(const counted_ptr&amp; rhs);
  template&lt;typename rhs_pointee_type&gt;
    counted_ptr&amp; operator=(const specialised_counted_ptr_base&lt;rhs_pointee_type&gt;&amp; rhs);
  void reset(pointee_type* p); /// Delete existing contents (and take ownership of p)
  void swap(base_type&amp; with) throw():/// Swaps contents with &quot;with&quot;
};
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e158" id="d0e158"></a>uncounted_ptr
interface</h3>
</div>
<pre class="programlisting">
template&lt;typename pointee_type&gt;
class uncounted_ptr : public specialised_counted_ptr_base&lt;pointee_type&gt;
{
  typedef specialised_counted_ptr_base&lt;pointee_type&gt; base_type;

public:
  /** Construction */
  uncounted_ptr(); /// &quot;0 initialised&quot; pointer
  template&lt;typename rhs_pointee_type&gt;
  uncounted_ptr( const specialised_counted_ptr_base&lt;rhs_pointee_type&gt;&amp; rhs); /// Take value of rhs
  ~uncounted_ptr() throw();

  /** Accessors */
  pointee_type* get() const; /// Returns contents
  pointee_type* operator-&gt;() const; /// Dereference op
  pointee_type&amp; operator*() const; ///  Dereference op

  /** Mutators */
  template&lt;typename rhs_pointee_type&gt;
  uncounted_ptr&amp; operator=( const specialised_counted_ptr_base&lt;rhs_pointee_type&gt;&amp; rhs);
  void reset(pointee_type* p); /// Delete existing contents (and take ownership of p)
  void swap(base_type&amp; with) throw(); /// Swaps contents with &quot;with&quot;
};
</pre></div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
