    <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  :: A Review of cow_ptr&lt;type&gt;</title>
        <link>https://members.accu.org/index.php/articles/530</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 #32 - Jun 1999</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/c172/">32</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+172/">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;A Review of cow_ptr&lt;type&gt;</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 June 1999 17:50:53 +01:00 or Sat, 26 June 1999 17:50:53 +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>Intro</h2>
</div>
<p>In my previous article I looked at a copy-on-write pointer
class. I had planned that this article would follow in the normal
way. Things rarely happen exactly as you plan them. Instead, I'm
going to use this article to review the previous
article<sup>[<a name="d0e23" href="#ftn.d0e23" id=
"d0e23">1</a>]</sup>. I think this is an honest approach. It is
after all how most developers work. You don't write code in a
straight line.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e27" id="d0e27"></a>Style follows
audience</h2>
</div>
<p>Astute reader Mr Kevlin Henney of Bristol kindly read through
the previous article before I submitted it. He asked why I had
mixed the style of my const declarations. Ah yes. In the previous
article at one point I wrote this</p>
<pre class="programlisting">
class string::char_reference
{
  ...
private:
  string * const target;
  size_t const index;
};
</pre>
<p>I think my train of thought for this experiment started with
<tt class="varname">target</tt>. There is no const-choice for
<tt class="varname">target</tt>. If I want <tt class=
"varname">target</tt> to be <tt class="literal">const</tt> it has
to be as it is. Ok, but what about <tt class="varname">index</tt>.
If I want <tt class="varname">index</tt> to be <tt class=
"literal">const</tt> there are two choices&hellip;</p>
<pre class="programlisting">
const size_t index;  // conventional
size_t const index;  // not-so-conventional
</pre>
<p>The first obvious point is that using the not-so-conventional
style for <tt class="varname">index</tt> means that <tt class=
"varname">target</tt> and <tt class="varname">index</tt> acquire
similar looking declarations. There's something else too though. It
was pretty subconscious but looking at it now and trying to
vocalise the difference I think I can see it. It's a matter of
emphasis. The not-so-conventional style places the <tt class=
"literal">const</tt> near to the identifier (with the effect that
the type-name is always the leftmost identifier), whereas the
conventional-style places the <tt class="literal">const</tt> near
to the type-name. The question is what is <tt class=
"literal">const</tt>? Is it the type or is it the entity referred
to by <tt class="varname">index</tt>? It's both really, but it
comes back to types and expressions. Do you want to focus on the
type of <tt class="varname">index</tt> or on the use of <tt class=
"varname">index</tt> in expressions? Given that <tt class=
"varname">index</tt> is a private data member it's fair to say that
the primary audience for <tt class="varname">index</tt> is the
class-implementor. And of course they will be using <tt class=
"varname">index</tt> in expressions. Clear as mud?</p>
<p>However, at another point in the article I wrote&hellip;</p>
<pre class="programlisting">
cow_ptr(const cow_ptr &amp; rhs); // c'tor declaration
</pre>
<p>To make this consistent with the index-style, surely it would
need to be</p>
<pre class="programlisting">
cow_ptr(cow_ptr const &amp; rhs);
</pre>
<p>I don't think so. This is a very different case. This is public
method. I think it's fair to say that the primary audience for this
is the class-clients. They won't be using <i class=
"parameter"><tt>rhs</tt></i> in expressions. They'll be supplying
something for <i class="parameter"><tt>rhs</tt></i> to bind to.
Their main consideration is the type of <i class=
"parameter"><tt>rhs</tt></i>. So, given that I've chosen to use the
expression-style when I want to focus on the implementation it
makes sense to use the type-style when I want to focus on the
interface. It provides a nice interface/implementation distinction
too.</p>
<p>There something else to add to this. It's the observation that
these function declarations must have a matching function
definition. Should the function definition use the type-style or
the expression-style? I think that it should use the
type-style&hellip;</p>
<pre class="programlisting">
template&lt;typename type&gt;
cow_ptr&lt;type&gt;::cow_ptr(const cow_ptr &amp; rhs) 
&hellip;
{
  &hellip;
}
</pre>
<p>Note though that I'm happy for the names of the parameters to be
different from declaration to definition. I think that's entirely
reasonable. Again it's all about the target audience. For the
declaration the audience are the users, and their focus should be
what is happening. For the definition the audience is the
implementor, and their focus is <span class=
"emphasis"><em>how</em></span> it's happening. I think that's a
healthy difference.</p>
<p>So there you have it; my limited excursion into
expression-style. I don't go the whole hog with it. But some do.
Dan Saks does. Francis uses it in his EXE columns too. I recall one
reason for their enthusiastic embrace was based on reading
declarations. The argument is that you can then read declarations
from right to left.</p>
<pre class="programlisting">
size_t const index; 
</pre>
<p>Index is a const size_t. It does <span class=
"emphasis"><em>appear</em></span> to work. Don't get me wrong now -
I think reading code is very important. Code is rarely spoken aloud
- it's read. Which is why how code looks is so important. Layout
matters. It's just that I don't think that you read code
right-to-left or left-to-right! I think an experienced C/C++
programmer slurps up whole statements at a time.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e134" id="d0e134"></a>Style follows
style</h2>
</div>
<p>One more style issue. Member initialisation lists. In my
original Overload 31 submission I wrote&hellip;</p>
<pre class="programlisting">
template&lt;typename type&gt;
cow_ptr&lt;type&gt;::cow_ptr(const cow_ptr &amp; rhs)
  : ptr(rhs.ptr)
  , count(rhs.count)
{
  &hellip;
}
</pre>
<p>However, in the published article it ended up as&hellip;</p>
<pre class="programlisting">
template&lt;typename type&gt;
cow_ptr&lt;type&gt;::cow_ptr(const cow_ptr &amp; rhs)
  : ptr(rhs.ptr), count(rhs.count)
{
  &hellip;
}
</pre>
<p>The former style, with each initialisation on its own line, is
the style I prefer for member initialisation lists. There are a
couple of reasons. Firstly it just fits on the page better.
Particularly if I have a couple of longish identifiers. Secondly it
separates the colon-comma punctuation from the essential
initialisations. Thirdly it matches closely the declaration style I
use in the class definition. In the class definition I declare
identifiers one per line. I write&hellip;.</p>
<pre class="programlisting">
template&lt;typename type&gt;
class cow_ptr
{
  &hellip;
private: // state
  type * ptr;
  size_t * count;
};
</pre>
<p>I don't write&hellip;</p>
<pre class="programlisting">
template&lt;typename type&gt;
class cow_ptr
{
  &hellip;
private: // state
  type * ptr;  size_t * count;
};
</pre>
<p>It all comes back to simplicity. See below.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e155" id="d0e155"></a>Exception
unsafety</h2>
</div>
<p>Here's the constructor for <tt class=
"classname">cow_ptr&lt;&gt;</tt> again</p>
<pre class="programlisting">
template&lt;typename type&gt;
cow_ptr&lt;type&gt;::cow_ptr(type * p)
  : ptr(p), count(new size_t(1))
{
  // all done
}
</pre>
<p>and here's how it was used&hellip;</p>
<pre class="programlisting">
cow_ptr&lt;type&gt; unshared(new type(*ptr));
</pre>
<p>This is not exception safe. And remember this is a template
class. We don't know how big the potential leak is because we don't
know what type is. Ooops.</p>
<pre class="programlisting">
template&lt;typename type&gt;
cow_ptr&lt;type&gt;::cow_ptr(type * p)
{
  auto_ptr&lt;type&gt; safe(p);
  count = new size_t(1);
  ptr = safe.release();
}
</pre>
<p>That's better.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e175" id="d0e175"></a>Refactor</h2>
</div>
<p>The longer I work in software the more I become convinced that
simplicity is the key. Yet somehow it's really hard to write
<span class="emphasis"><em>really</em></span> simple code. It's as
though the programmer's psyche somehow rejects simplicity. I can
imagine a hard-core hacker pointing to a particularly dense piece
of code they've just written and proclaiming loudly &quot;I wrote that.
Bet you can't understand it. I can. I'm dead 'ard me&quot;. ;-&gt;
Simplicity is one of those things that is hard to define but you
know it when you see it. To quote John Pawson,</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;The minimum could be defined as the perfection that an artefact
achieves when it is no longer possible to improve it by
subtraction&quot; [<a href="#Pawson">Pawson</a>].</p>
</blockquote>
</div>
<p>Code-simplicity and code-duplication don't sit well together.
I'm afraid there was some code-duplication in my previous article.
I wrote&hellip;</p>
<pre class="programlisting">
template&lt;typename type&gt;
cow_ptr&lt;type&gt; &amp;
cow_ptr&lt;type&gt;::operator=(const cow_ptr &amp; rhs)
{
  ++*rhs.count;
  if (--*count == 0)
  {
    delete count;
    delete ptr;
  }
  ptr = rhs.ptr;
  count = rhs.count;
  return *this;  
}

template&lt;typename type&gt;
cow_ptr&lt;type&gt; &amp;
cow_ptr&lt;type&gt;::~cow_ptr()
{
  if (--*count == 0)
  {
    delete count;
    delete ptr;
  }
}
</pre>
<p>The duplication is plain to see. Let's try refactoring to avoid
the duplication. One approach is to simply extract the common code
and put it in a new private method.</p>
<pre class="programlisting">
template&lt;typename type&gt;
void cow_ptr&lt;type&gt;::decrement() const
{
  if (--*count == 0)
  {
    delete count;
    delete ptr;
  }
}

template&lt;typename type&gt;
cow_ptr&lt;type&gt; &amp;
cow_ptr&lt;type&gt;::operator=(const cow_ptr &amp; rhs)
{
  ++*rhs.count;
  decrement();
  ptr = rhs.ptr;
  count = rhs.count;
  return *this;  
}

template&lt;typename type&gt;
cow_ptr&lt;type&gt; &amp;
cow_ptr&lt;type&gt;::~cow_ptr()
{
  decrement();
}
</pre>
<p>Now suppose we wanted to clear the cow_ptr pointer, that is to
reset it's pointer to null. At the moment we would have to jump
through a small hoop&hellip;</p>
<pre class="programlisting">
cow_ptr&lt;type&gt; ptr(new type(...));
...
ptr = cow_ptr&lt;type&gt;(0);  // clear pointer 
</pre>
<p>It's a small but perhaps not-so-obvious step to promote the
private decrement() into a public clear().</p>
<pre class="programlisting">
template&lt;typename type&gt;
cow_ptr&lt;type&gt; &amp;
cow_ptr&lt;type&gt;::~cow_ptr()
{
  clear();
}

template&lt;typename type&gt;
cow_ptr&lt;type&gt;::operator=(const cow_ptr &amp; rhs)
{
  ++*rhs.count;
  clear();
  ptr = rhs.ptr;
  count = rhs.count;
  return *this;  
}

template&lt;typename type&gt;
void cow_ptr&lt;type&gt;::clear()
{
  if (--*count == 0)
  {
    delete count;
    delete ptr;

    count = 0;
    ptr = 0;
  }
}
</pre>
<p>There's still a potential problem with the assignment operator
though. It's not exception safe. To fix this we can use an approach
based on the &quot;Resource Acquisition is Initialisation&quot;
idiom<sup>[<a name="d0e207" href="#ftn.d0e207" id=
"d0e207">2</a>]</sup>. This requires a new constructor, which would
be private&hellip;</p>
<pre class="programlisting">
tempate&lt;typename type&gt;
cow_ptr&lt;type&gt;::cow_ptr(type * p, size_t * c) throw()
: ptr(p)
, count(c )
{
  // all done
}

template&lt;typename type&gt;
cow_ptr&lt;type&gt; &amp;
cow_ptr&lt;type&gt;::operator=(const cow_ptr &amp; rhs)
{
  cow_ptr old_self(ptr, count);
  ptr = rhs.ptr;
  count = rhs.count;
  ++*count;
  return *this;  
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e213" id="d0e213"></a>Refactor</h2>
</div>
<p>I'm afraid there was also some duplication elsewhere...</p>
<pre class="programlisting">
string::body::body(const char * literal)
{
cached_length = ::strlen(literal);
  text = new char[cached_length + 1];
  ::strcpy(text, literal);
}

string::body::body(const body &amp; rhs)
  : text(new char[rhs.cached_length + 1])
  , cached_length(rhs.cached_length)
{
  ::strcpy(text, rhs.text);
}
</pre>
<p>Code on a printed page feels different to code on the screen.
These grate on my sensibilities. The first <span class=
"emphasis"><em>assigns</em></span> to <tt class=
"varname">cached_length</tt> and then to <tt class=
"varname">text</tt>. The second initialises <tt class=
"varname">text</tt> and then <tt class=
"varname">cached_length</tt>. Refactor. Here's my first
attempt&hellip;</p>
<pre class="programlisting">
string::body::initialise(const char * literal)
{
cached_length = ::strlen(literal) ;
  text = new char[cached_length + 1];
  ::strcpy(text, literal);
}

string::body::body(const char * literal)
{
  initialise(literal);
}

string::body::body(const body &amp; rhs)
{
  initialise(rhs.text);
}
</pre>
<p>This is better. I can still see a flaw though. The copy
constructor is needlessly recalculating the length of the text.
Here's my second attempt&hellip;</p>
<pre class="programlisting">
string::body::initialise(const char * literal, size_t length)
{
cached_length = length;
  text = new char[length + 1];
  ::strcpy(text, literal);
}

string::body::body(const char * literal)
{
  initialise(literal, ::strlen(literal));
}

string::body::body(const body &amp; rhs)
{
  initialise(rhs.text, rhs.cached_length);
}
</pre>
<p>Ban <span class="emphasis"><em>all</em></span> duplicate
code.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e248" id="d0e248"></a>Explicit</h2>
</div>
<p>Following on nicely let's have a careful look at those two
<tt class="varname">string::body</tt> constructors. The sole
purpose of these two constructors is to be called explicitly. There
is no reason I can think of why you'd want to use <tt class=
"varname">string::body</tt> objects as value parameters to a
function, or as value return types from a function. They can be
made explicit.</p>
<pre class="programlisting">
struct string::body
{
  explicit body(const char * literal);  
  explicit body(const body &amp; rhs);
  ...
};
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e261" id="d0e261"></a>Typos</h2>
</div>
<p>There were a couple of typos in the previous article. A
declaration somehow acquired an extra
right-parentheses<sup>[<a name="d0e266" href="#ftn.d0e266" id=
"d0e266">3</a>]</sup>. The compiler would have balked at that of
course. The more insidious typos are always the ones that aren't
compile-time error. Such as...</p>
<pre class="programlisting">
class string::char_reference
{
  ...
  char_reference operator=(char new_value);
  ...
};
</pre>
<p>This assignment operator returns a <tt class=
"type">char_reference</tt> by value. It should of course return a
<tt class="type">char_reference</tt> by reference.</p>
<pre class="programlisting">
class string::char_reference
{
  ...
  char_reference &amp; operator=(char new_value);
  ...
};
</pre>
<p>My thanks again to Kevlin for several comments that improved
this article. That's all for now. Cheers, JJ.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e284" id="d0e284"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Pawson" id="Pawson"></a>
<p class="bibliomixed">[Pawson] Minimum. by John Pawson. Phaidon
Press. 0 7148 3817 9. I first learned of Minimum in a reference in
one of Kevlin's talks - The Road to Software Architecture. You can
find all his talks at <span class="bibliomisc"><a href=
"http://techland.qatraining.com/" target=
"_top">http://techland.qatraining.com/</a></span>.</p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c2" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e23" href="#d0e23" id=
"ftn.d0e23">1</a>]</sup> I'm tempted to repeat this as a pattern:
article,review; article,review; article,review...</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e207" href="#d0e207" id=
"ftn.d0e207">2</a>]</sup> What a catchy name ;-&gt;</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e266" href="#d0e266" id=
"ftn.d0e266">3</a>]</sup> Also known as &quot;theses&quot;. And of course the
left-parentheses is then called &quot;paren&quot;.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
