    <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  :: Interpreting &quot;Supporting the 'Cheshire Cat' Idiom&quot;</title>
        <link>https://members.accu.org/index.php/journals/482</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 #38 - Jul 2000 + Design of applications and programs</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/c166/">38</a>
                    (6)
<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/c67/">Design</a>
                    (236)
<br />

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

                    -                        <a href="https://members.accu.org/index.php/journals/c166+67/">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;Interpreting &quot;Supporting the 'Cheshire Cat' Idiom&quot;</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 July 2000 17:50:57 +01:00 or Wed, 26 July 2000 17:50:57 +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="d0e25" id="d0e25"></a></h2>
</div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>One of the nice thing about being Treasurer of the ACCU was the
opportunity to learn by rubbing shoulders with &quot;real&quot; programmers.
Often after committee meetings or phone calls with officers on
Association business we would drift into talking about programming.
One such conversation with AG lead to the idea that we could take
his article on the Cheshire Cat and run a recorded discussion where
I could ask the sort of question that maybe a student/learner would
ask a Tutor or mentor. What you see below is the result, I hope
that by asking some questions I learn from the answers and that
maybe others who are to shy to ask will also learn. I also hope
that this project will reassure potential authors for CVu and
Overload that there is a need for teaching as well as cutting edge
articles.</p>
</dd>
</dl>
</div>
<p>The <i class="firstterm">Cheshire Cat</i> idiom is a great
solution to a set of problems that have existed since the
pre-history of C++. This idiom first emerged in the late '80s in a
cross-platform GUI class library called CommonView and was
described by John Carolan (&quot;<i class="citetitle">Constructing
bullet-proof classes&quot; - Proceedings: C++ at Work '89</i> - SIGS).
It has been reinvented a number of times since and is also known as
&quot;compilation firewall&quot; and as &quot;pimpl&quot;. The &quot;Gang of Four&quot;
classifies it as a special case of the &quot;Bridge&quot; pattern (ISBN
0-201-63361-2 <i class="citetitle">Design Pattern</i> -
Addison-Wesley).</p>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>Is this really a pattern? I had got the impression that patterns
were far more sophisticated and had avoided them as being beyond my
comprehension. What actually is a pattern? How much do I need to
know about them?&quot;</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>What constitutes a &quot;Pattern&quot; is a subject of debate amongst the
experts. I'd be happy calling &quot;Bridge&quot; a pattern, but I use the
less ambitious term &quot;idiom&quot; where both the issues to be resolved
and the solution are language specific - which is the case with
&quot;Cheshire Cat&quot;. Patterns are not inherently hard to understand -
they are descriptions of recurring design problems and
corresponding &quot;neat&quot; solutions. Although some presentations of
patterns can be difficult much of the material will give the
experienced developer the warm glow of familiarity (I said they
were recurring problems) or the warm glow of embarrassment upon
seeing a much neater solution than the one she's just
implemented.&quot;</p>
</dd>
</dl>
</div>
<p>More recently I have examined the development of this idiom in
an article <i class="citetitle">Ending with the Grin</i> in EXE
magazine (March 2000), the latter part of the EXE article describes
the use of a smart pointer - <tt class=
"classname">arg::grin_ptr&lt;&gt;</tt> - that simplifies the
writing of &quot;Cheshire Cat&quot; classes. The current article discusses
the implementation of this smart pointer.</p>
<p>However, before looking at this template class let us make
review the problems the &quot;Cheshire Cat&quot; idiom solves and the way in
which it resolves them. These problems stem from three areas:</p>
<p>Ensuring that a header file includes nothing that the client
code needn't be aware of. (In the case of CommonView, this includes
the native windowing APIs.)</p>
<p>Making it possible to distribute updates to object code library
without requiring the client code to be recompiled. If a class
definition (or anything else in a header) changes, then any
compilation unit that includes it must be recompiled.</p>
<p>Protecting intellectual property by concealing implementation
techniques used.</p>
<p>Which of these is most important to you will differ according to
circumstance, but the &quot;Cheshire Cat&quot; idiom addresses them all.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e76" id="d0e76"></a>The &quot;classical&quot;
Cheshire Cat</h2>
</div>
<p>When Glockenspiel (the suppliers of CommonView) started
developing their cross-platform GUI library they were influenced by
all three of the above reasons for hiding the implementation. Here
is a simplified telephone list class implemented in the style of
the CommonView library:</p>
<pre class="programlisting">
struct phone_list_implementation;

class phone_list
{
public:
  phone_list(const char *name);
  phone_list(const phone_list&amp; rhs);
  phone_list&amp; operator
              (const phone_list&amp; rhs);
  ~phone_list();

  const char* list_name();
  const char* find_number
                (const char *person);
  void add(const char *name
        , const char *number);
private:
  phone_list_implementation* grin;
};
</pre>
<p>Note the need for a copy constructor and assignment operator.
These are required because <tt class="classname">phone_list</tt>
owns the <tt class="classname">phone_list_implementation</tt> to
which it holds a pointer. (The default behaviour of just copying
the pointer value is obviously inappropriate.)</p>
<p>Once you've written a few classes using this idiom it will occur
to you that you are writing the same functions again and again to
manage the implementation. Specifically the copy constructor,
assignment operator and destructor of a Cheshire Cat class are
generic - they always look the same, they only differ in the types
of the interface and implementation classes.</p>
<p>This sounds like a job for a template. A template that looks
after an implementation object allocated on the heap, and ensures
it is copied or deleted when appropriate. It is tempting to reach
for the standard library, but the closest thing we find there is
<tt class="classname">auto_ptr&lt;&gt;</tt>.</p>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>I can see why we need to be careful about copy and assignment
operations but do we have to as careful if we can promise that we
only create one instance of phone list and that it is not copied or
assigned by our code. In other words will the compiler sneak in
copy or assignment operation unbeknown to the code writer. I accept
that when writing a library for general use this would be an
unacceptable limitation.</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>I would like to say that this is the difference between an
amateur approach and that of a professional - because you can say
it in the code that you won't be copying or assigning an object. By
declaring a private copy constructor and assignment operator (and
not implementing them) you'll ensure either a compile error or a
link error if you break this guarantee. Sadly, if I were to say
such a thing I'd also have to admit that there are some very highly
paid &quot;amateurs&quot; in the industry.</p>
<p>If the author of a class fails to declare these methods, then
the compiler generates inline versions based on memberwise copying
- and copying a pointer member rarely gives the correct result.</p>
<p>On your final point about a library for general use - even when
I write &quot;throw away&quot; code for quick &amp; dirty utilities I find
that someone on the project will mine it for solutions to their
problems and re-apply it in situations I cannot predict. (I admit
that sometimes that someone is me months or years later - but I am
more careful than most about ensuring that the code works in the
new context.) It is simpler to ensure that the code cannot be
abused than to enter a debate about the sanity of this
practice.&quot;</p>
</dd>
<dt><span class="term">AN:</span></dt>
<dd>
<p>A slight diversion here, is this the reason that for some of the
failure of code re-use? Have people written code with specific
applications in mind and then the code has just not been
sufficiently widely applicable for re-use?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>I think the main reason for the failure of re-use is the failure
of management to identify the development of reusable components as
a separately resourced project. It is too often something that is
expected to happen for free as a side effect of the first project
that needs to incorporate a facility. Either the necessary
resources to tackle the more general solution are not made
available in the project budget, or if they are available they are
expended on work with a more direct application to the problem in
hand.</p>
</dd>
</dl>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e127" id="d0e127"></a>On <tt class=
"classname">std::auto_ptr&lt;&gt;</tt></h2>
</div>
<p>Although <tt class="classname">auto_ptr&lt;&gt;</tt> does not
meet our current needs it is instructive to know why since at least
one of the reasons is not immediately obvious&hellip;</p>
<p>The standard library <tt class="classname">auto_ptr&lt;&gt;</tt>
has what I will politely describe as &quot;interesting&quot; copy semantics.
Specifically, if one <tt class="classname">auto_ptr&lt;&gt;</tt> is
assigned (or copy constructed) from another then they are both
changed - the <tt class="classname">auto_ptr&lt;&gt;</tt> that
originally owned the object loses ownership and becomes 0. This is
a trap for the unwary! There are situations that call for this
behaviour, but on this occasions the copy semantics cause a
problem.</p>
<p>If we substitute <tt class=
"literal">auto_ptr&lt;implementation&gt;</tt> for <tt class=
"type">implementation*</tt> in the <tt class=
"classname">phone_list</tt> class we will find that we still need
to write the copy constructor and assignment operator. (To avoid an
<tt class="classname">implementation</tt> being passed from one
<tt class="classname">phone_list</tt> to another.) Fortunately the
compiler detects the non-standard copy and assignment of the
<tt class="classname">auto_ptr&lt;&gt;</tt> data member and issue a
diagnostic to prompt us to write these functions.</p>
<p>A subtler problem is that we also need to write the destructor -
if we don't, the one the compiler silently generates for us will
not correctly destroy the <tt class=
"classname">implementation</tt>. This is because by default the
<tt class="classname">phone_list</tt> destructor is generated by
the compiler without having seen the class definition for
<tt class="classname">implementation</tt>. This forces it to
instantiate the <tt class="classname">auto_ptr&lt;&gt;</tt>
destructor without having seen the class definition for <tt class=
"classname">implementation</tt>. If <tt class=
"classname">implementation</tt> has a non-trivial destructor this
leads to &quot;undefined behaviour&quot;. A good compiler may give a warning
about deleting an incomplete type. But the language standard only
allows the compiler to refuse to compile the code (a helpful form
of &quot;undefined behaviour&quot;) if there is a non-trivial destructor -
and the compiler cannot know this at compile time without first
seeing the definition.</p>
<p>Using <tt class="classname">auto_ptr&lt;&gt;</tt> would save us
nothing - we would still need to write the copy constructor,
assignment operator and destructor.</p>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>Every mention of <tt class="classname">auto_ptr&lt;&gt;</tt> in
books and magazines seems so loaded with caveats and warnings that
I wonder what use is it to a learning programmer? Just to reassure
me can someone give me an example of where <tt class=
"classname">auto_ptr&lt;&gt;</tt> can be safely used.</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>I refuse to defend <tt class="classname">auto_ptr</tt>! I
believe that its inclusion in the standard library as the sole
representative of the possible range of smart pointers was a
mistake. (If there had been half a dozen others - see my website
for a few of the possibilities, or none, then I would have less
complaint.) It distracts the learning programmer from the need to
identify a suitable smart pointer for the needs of the moment.</p>
<p>Sorry, to take up your challenge:</p>
<pre class="programlisting">
void foo()
{
  const auto_ptr&lt;bar&gt; pbar(condition ? 
        new default_bar() 
      : new alternate_bar());
  . . .
  pbar-&gt;f();
  . . .
};
</pre></dd>
<dt><span class="term">AN:</span></dt>
<dd>
<p>So really <tt class="classname">auto_ptr&lt;&gt;</tt> is but one
example of a concept of smart pointers and I should learn more
about this concept. Then I use or design the proper pointer for a
job, not try (and fail!!!) to make the job suit <tt class=
"classname">auto_ptr&lt;&gt;</tt>?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>Precisely. In fact that is the starting point for the current
article - there was a discussion on <tt class=
"literal">comp.lang.c++ moderated</tt> where the participants were
discussing the techniques needed to make the &quot;Cheshire Cat&quot; job
suitable for <tt class="classname">auto_ptr&lt;&gt;</tt>. I
realised that, since the last time I considered the matter, I had
acquired the techniques necessary to implement a suitable smart
pointer type. So I did.</p>
</dd>
</dl>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e243" id="d0e243"></a><tt class=
"classname">arg::grin_ptr&lt;&gt;</tt></h2>
</div>
<p>Let us suppose for a moment that such a smart pointer exists and
is called <tt class="classname">arg::grin_ptr&lt;&gt;</tt>. This
would allow the <tt class="classname">phone_list</tt> class to be
rewritten as shown in listing 1.</p>
<div class="sidebar">
<p class="title c2">Listing 1: Using <tt class=
"classname">arg::grin_ptr&lt;&gt;</tt></p>
<pre class="programlisting">
class phone_list
{
public:
  explicit phone_list(std::string name);

  std::string name() const;

  std::pair&lt;bool, std::string&gt;
      number(std::string person) const;

  phone_list&amp; add (std::string name,
                 std::string number);
private:
  class implementation;
  arg::grin_ptr&lt;implementation&gt; grin;
};
</pre></div>
<p>Note that there is no longer a need to supply the copy
constructor, assignment operator, or destructor as we are assuming
that the necessary logic is supplied by the <tt class=
"classname">grin_ptr&lt;&gt;</tt> template. I have also taken the
opportunity to use a more contemporary style of C++, but the ideas
are the same. The resulting simplification looks good, but how can
it be achieved?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e267" id="d0e267"></a>Implementing
arg::grin_ptr&lt;&gt;</h2>
</div>
<p>The principle problem to overcome in implementing <tt class=
"classname">grin_ptr&lt;&gt;</tt> is the last point mentioned in
the discussion of auto_ptr&lt;&gt; - how to cope with deleting an
incomplete type. The destructor of <tt class=
"classname">grin_ptr&lt;&gt;</tt> cannot be a simple &quot;<tt class=
"literal">delete p;</tt>&quot; because at the point of instantiation the
pointer is to an &quot;incomplete type&quot;.</p>
<p>To avoid this I make use of the fact that the constructor for
<tt class="classname">grin_ptr&lt;&gt;</tt> is instantiated in the
implementation file, where the class definition for <tt class=
"classname">implementation</tt> resides. At this point I force the
compiler to generate a deletion function using a trick I first saw
in Richard Hickey's article Callbacks in <i class="citetitle">C++
Using Template Functors</i> (C ++ Gems ISBN 1 884842 37 2): the
constructor stores a pointer to this function in the <tt class=
"classname">grin_ptr&lt;&gt;</tt>. This provides a safe method for
the destructor to delete the object it owns. The point of passing
around function pointers instead of the apparently more natural use
of virtual member functions is that everything can be done &quot;by
value&quot; and no dynamic allocation is required.</p>
<p>A similar function is used for copying the object, so because it
contains two function pointers a <tt class=
"classname">grin_ptr&lt;&gt;</tt> is a bit bigger than a raw
pointer but this isn't likely to be an issue in most uses. The
complete code for <tt class="classname">grin_ptr&lt;&gt;</tt> is
shown in listing 2:</p>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>This is where I hit my intellectual brick wall!!!</p>
<p>Let me get this straight, we need a pointer to an object but we
must have very specific action when we copy a class/structure
containing the pointer. Also when a class/structure that contains
the pointer has its destructor called then we need to call the
destructor of what is pointed to?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>Correct, you are with me so far!</p>
</dd>
<dt><span class="term">AN:</span></dt>
<dd>
<p>Looking at the code I have problems at two intermingled levels,
the structure and the detail of each line. I have put some comments
in the code.</p>
<p>I see that <tt class="varname">p</tt> is the &quot;real&quot; pointer but
am rather confused. I assume that the function calls in Listing 1
are implemented as calls to the thing pointed to by <tt class=
"varname">p</tt>. Thus the function declared as</p>
<pre class="programlisting">
std::pair&lt;bool, std::string&gt;
       number(std::string person) const;
</pre>
<p>will have code like</p>
<pre class="programlisting">
std::pair&lt;bool, std::string&gt;
   phonelist::number(std::string person)
{
  return p-&gt;ps_number(person) ;
}
</pre></dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>Looking at the original article I see that I failed to mention
that the members functions just forward to the implementation
class. Thanks for pulling me up on this - it is very easy to
misjudge an audience and assume background knowledge. Since you are
unfamiliar with the idiom you did well to get this close. Only a
small correction is required - remember that <tt class=
"classname">phonelist</tt> can only &quot;see&quot; the externals - the
actual code is:</p>
<pre class="programlisting">
std::pair&lt;bool, std::string&gt;
  phonelist::number(std::string person)
{
  return grin-&gt;number(person);
}
</pre>
<p>This (behind the scenes, and inlined in a manner that ought to
generate extra no code) calls the indirection operator which
replaces the sub expression &quot;<tt class="literal">grin-&gt;</tt>&quot;
with the value of <tt class="varname">grin::p</tt>. Of course,
thinking at this level is akin to thinking about which controls you
are using when you are driving - liable to cause accidents.</p>
<p><tt class="classname">grin_ptr</tt> is designed to act &quot;just
like&quot; a pointer in all relevant ways while taking the burden of
ownership management. Naturally, &quot;all relevant ways&quot; does not
include such things as support for pointer arithmetic since this is
inappropriate for pointers used in implementing &quot;Cheshire Cat&quot;.
(Acting &quot;just like a pointer in all relevant ways&quot; is the signature
of a &quot;smart pointer&quot;.)</p>
<p>By using a compatible substitute for a &quot;real&quot; pointer you save
yourself the need to write boilerplate code, everything else is the
same. (We are both old enough to remember manual chokes, the advent
of automatic chokes and/or fuel injection in popular models did not
significantly change the way we drive, just removed a source of
errors.)</p>
</dd>
</dl>
</div>
<div class="sidebar">
<p class="title c2">Listing 2: arg::grin_ptr&lt;&gt;</p>
<pre class="programlisting">
template&lt;typename p_type&gt;
class grin_ptr
{
// Pointers to utility functions
  typedef void (*delete_ftn)(p_type* p);
  typedef p_type* 
          (*copy_ftn)(const p_type* p);
public:
  explicit grin_ptr(p_type* pointee) 
    : do_copy(&amp;my_copy_ftn), p(pointee), do_delete(my_delete_ftn) {}
</pre></div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>Why do we use explicit here? The other statements are merely
initialisers for the various members?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>To answer the second question first: yes, this is the syntax for
initialising the class members. The reason for using explicit is to
prevent the user could accidentally converting a pointer (of type
<tt class="type">T*</tt> say) to a smart pointer (type <tt class=
"classname">grin_ptr&lt;T&gt;</tt>) since the temporary smart
pointer would assume ownership of the original, and delete it at a
point the user does not expect.</p>
</dd>
</dl>
</div>
<div class="sidebar">
<pre class="programlisting">
  grin_ptr(const grin_ptr&amp; rhs);
</pre></div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>This is the copy constructor?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>Yes.</p>
</dd>
</dl>
</div>
<div class="sidebar">
<pre class="programlisting">
  ~grin_ptr() throw() { do_delete(p); }
</pre></div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>This is the destructor which calls <tt class=
"methodname">do_delete</tt>.</p>
</dd>
</dl>
</div>
<div class="sidebar">
<pre class="programlisting">
  const p_type* get() const { return p; }
  p_type* get() { return p; }
  const p_type* operator-&gt;() const {
    return p; 
  }
  p_type* operator-&gt;() { return p; }
  const p_type&amp; operator*() const { 
    return *p; 
}
</pre></div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>are we overloading the operator '<tt class="methodname">*</tt>'
here?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>Yes, this is the dereference operator.</p>
</dd>
<dt><span class="term">AN:</span></dt>
<dd>
<p>Glad you reminded me, most of my work is numerical and I always
get confused by the use of &quot;<tt class="methodname">*</tt>&quot; to
dereference and to multiply.</p>
</dd>
</dl>
</div>
<div class="sidebar">
<pre class="programlisting">
  p_type&amp; operator*() { return *p; }
  void swap(grin_ptr&amp; with) throw() { 
    p_type* pp = p; 
    p = with.p; with.p = pp; 
  }
    grin_ptr&amp; operator= (
                const grin_ptr&amp; rhs);
private:
  copy_ftn  do_copy;
  p_type*    p;
  delete_ftn  do_delete;
</pre></div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>The two lines <tt class="classname">copy_ftn</tt> and <tt class=
"classname">delete_ftn</tt> confuse me. <tt class=
"classname">copy_ftn</tt> and <tt class="classname">delete_ftn</tt>
are what? Did I miss their definition? They seem to be pointer like
but are they?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>If you look back to the top of the class definition you will see
a couple of <tt class="literal">typedef</tt>s. These declare
<tt class="classname">copy_ftn</tt> and <tt class=
"classname">delete_ftn</tt> as pointers to functions. I cannot
think of a good reason for separating the declarations from the
point of use like this - I should probably move them to this
vicinity.</p>
</dd>
</dl>
</div>
<div class="sidebar">
<pre class="programlisting">
  static void my_delete_ftn(p_type* p) {
    delete p;
  }
</pre></div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>What is the relationship between <tt class=
"methodname">my_delete_ftn</tt> and <tt class=
"classname">delete_ftn</tt>. Are they both the same type of
object?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>They are related, but not quite the same, <tt class=
"classname">delete_ftn</tt> is a type whose instances can hold a
pointer to a function with they same signature as <tt class=
"methodname">my_delete_ftn</tt>.</p>
</dd>
</dl>
</div>
<div class="sidebar">
<pre class="programlisting">
  static p_type* my_copy_ftn(
                    const p_type* p) {
    return deep_copy(p);
  }
};
template&lt;typename p_type&gt;
inline grin_ptr&lt;p_type&gt;::grin_ptr(
              const grin_ptr&amp; rhs)
    :  do_copy(rhs.do_copy),
      p(do_copy(rhs.p)),
      do_delete(rhs.do_delete) { }
</pre></div>
<div class="variablelist">
<dl>
<dt><span class="term">AN:</span></dt>
<dd>
<p>The impression is that there is a lot of work going on in the
constructor, exactly what is happening?</p>
</dd>
<dt><span class="term">AG:</span></dt>
<dd>
<p>The <tt class="classname">grin_ptr</tt> has three data members,
a pointer to a function that knows how to make copies of the
subject, a pointer to the subject and a pointer to a function that
knows how to delete the subject. In this copy constructor they are
initialised by copying the function pointers and using the first of
these functions to copy the subject.</p>
</dd>
</dl>
</div>
<div class="sidebar">
<pre class="programlisting">
template&lt;typename p_type&gt;
inline grin_ptr&lt;p_type&gt;&amp; grin_ptr&lt;p_type&gt;::operator=(
                const grin_ptr&amp; rhs){
  p_type* pp = do_copy(rhs.p);
  do_delete(p);
  p = pp;
  return *this;
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e531" id="d0e531"></a>Deep copying
with <tt class="classname">arg::deep_copy()</tt></h2>
</div>
<p>The copying mechanism is in fact a bit more flexible than the
current discussion would indicate, since the copying method has
also been factored out into the <tt class=
"classname">arg::deep_copy()</tt> algorithm but if you do nothing
special then copying will take place using <tt class="literal">new
implementation(*p);</tt> as you probably expect.</p>
<p>The <tt class="classname">arg::deep_copy()</tt> algorithm allows
a <tt class="methodname">clone()</tt> method (or any other name) to
be used to copy the owned object. The code for <tt class=
"methodname">deep_copy()</tt> is shown in listing 3:</p>
<div class="sidebar">
<p class="title c2">Listing 3: The <tt class=
"classname">arg::grin_ptr&lt;&gt;</tt> Algorithm</p>
<pre class="programlisting">
struct Cloneable {};

template&lt;class p_type&gt;
inline p_type* deep_copy(const p_type* p, const void*) 
{
  return p ? new p_type(*p) : 0;
}

template&lt;class p_type&gt;
inline p_type* deep_copy(const p_type *p, const cloneable *)
{
  return p ? p-&gt;clone() : 0;
}

template&lt;class p_type&gt;
inline p_type* deep_copy(const p_type *p, const Cloneable *)
{
  return p ? p-&gt;makeClone() : 0;
}

template&lt;class p_type&gt;
inline p_type* deep_copy(const p_type* p) 
{
  return deep_copy(p, p);
}
</pre></div>
<p>The effect is that: any class that inherits from <tt class=
"methodname">arg::clonable()</tt> will be copied by <tt class=
"literal">p-&gt;clone();</tt> and any class that inherits from
<tt class="classname">arg::Cloneable</tt> will be copied using
<tt class="literal">p-&gt;makeClone()</tt>. (These two versions
exist to support both my currently favoured naming style and the
one that I am required to use at work.) In addition any class that
has a <tt class="methodname">deep_copy()</tt> algorithm defined in
a suitable namespace will be copied using it in preference to the
above.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e580" id="d0e580"></a>In
conclusion</h2>
</div>
<p>In this article I have shown how it is possible to remove some
of the repetitive work from the development of &quot;Cheshire Cat&quot;. In
addition, I have put a sample implementation of <tt class=
"classname">grin_ptr&lt;&gt;</tt> into the &quot;arglib&quot; library on my
website: (<a href="http://www.octopull.demon.co.uk/arglib/" target=
"_top">http://www.octopull.demon.co.uk/arglib/</a>).</p>
<p>It would be possible to develop <tt class=
"classname">grin_ptr&lt;&gt;</tt> further and to implement a regime
known as &quot;copy on write&quot;. &quot;Copy on write&quot; shares the implementation
between interface classes unless or until one of them makes a
change (&quot;writes&quot;) to the implementation. Only at this point is a
copy taken of the implementation object.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
