    <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  :: To Grin Again</title>
        <link>https://members.accu.org/index.php/articles/1993</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 #72 - Apr 2006</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/c140/">72</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+140/">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;To Grin Again</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 04 April 2006 21:45:53 +01:00 or Tue, 04 April 2006 21:45:53 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<p>In the latter years of the last millennium there were a number of articles published that explored the design space of â€œsmart pointersâ€. That was in the days where there were loads of broken implementations available for download from the internet, but working ones â€“ like those in the Loki and Boost libraries â€“ were not to be found. </p>
<p>One of these pointers has come back to haunt me â€“ partly because I wrote it, but also because it meets a set of recurring requirements. Iâ€™d not looked at it for years, but a colleague was implementing a â€œCheshire Catâ€ class using Boostâ€™s <code>shared_ptr</code> [1] (which is a dubious choice as the copy and assignment semantics are completely wrong for this purpose) so I pointed him to my old article on <code>grin_ptr</code> [2]. This article has also been referenced by a couple of recent Overload articles, so I thought it was time to revisit the subject. </p>
<p>The first thing I discovered is that Iâ€™ve never submitted the article for publication in Overload (instead a heavily annotated version written with Allan Newton appeared in Overload 38 [3]). The second thing I discovered is that there were a number of improvements Iâ€™d like to make to both the code and to the article. What follows is the result. </p>
<h2>The â€œClassicalâ€ Cheshire Cat </h2>
<p>The â€œCheshire Catâ€ 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 [4]. It has been reinvented a number of times since and is also known as â€œCompilation Firewallâ€ and as â€œPimplâ€. The â€œGang of Fourâ€ [5] classifies it as a special case of the â€œBridgeâ€ pattern. These problems addressed by Cheshire Cat stem from three areas: </p>
<ol>
<li>
<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>
</li>
<li>
<p>Making it possible to distribute updated object code libraries 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>
</li>
<li>
<p>Protecting intellectual property by concealing implementation techniques used. </p>
</li>
</ol>
<p>Which of these is most important to you will differ according to circumstance, but the â€œCheshire Catâ€ idiom addresses them all. </p>
<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><code>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; 
}; 
</code></pre>

<p>Note the need for a copy constructor and assignment operator. These are required because <code>phone_list</code> owns the <code>phone_list_implementation</code> to which it holds a pointer. (The default behaviour of just copying the pointer value is obviously inappropriate.) </p>
<p>In the implementation file we can imagine that the phone_list member functions are implemented like this: </p>
<pre><code>const char* phonelist::find_number(const char* person) 
{ 
    return grin-&gt;number(person); 
} 
</code></pre>

<h2>The Motivation for grin_ptr </h2>
<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 <code>auto_ptr&lt;&gt;</code>. Even moving further afield to Boost we don't find a smart pointer with the desired semantics. </p>
<p>Let us suppose for a moment that such a smart pointer exists and is called <code>arg::grin_ptr&lt;&gt;</code>. This would allow the <code>phone_list</code> class to be rewritten as follows: </p>
<pre><code>class phone_list 
{ 
public:     
    explicit phone_list(std::string const&amp; name); 

    std::string name() const; 

    std::pair&lt;bool, std::string&gt; number(std::string const&amp; person) const; 

    phone_list&amp; add(std::string const&amp; name, std::string const&amp; number); 

private: 
    class implementation; 
    arg::grin_ptr&lt;implementation&gt; grin; 
}; 
</code></pre>

<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 <code>grin_ptr&lt;&gt;</code> template. (Iâ€™ve also taken the opportunity to use a more contemporary style of C++, by nesting implementation, using <code>const</code> and <code>std::string</code> but the ideas are the same.) </p>
<p>In the implementation file we can imagine that the phone_list member functions are implemented the same way as in the original. For example: </p>
<pre><code>std::pair&lt;bool, std::string&gt; 
phonelist::number(std::string const&amp; person) const 
{ 
    return grin-&gt;number(person); 
} 
</code></pre>

<p>The idea is for <code>grin_ptr&lt;&gt;</code> to act â€œjust likeâ€ a pointer in all relevant ways while taking the burden of ownership management. Naturally, â€œall relevant waysâ€ doesnâ€™t include such things as support for pointer arithmetic since this is inappropriate for pointers used in implementing â€œCheshire Catâ€.</p>
<p>By using a compatible substitute for a â€œrealâ€ pointer we avoid the need to write repetitive boilerplate code. Everything else is the same. </p>
<p>The resulting simplification looks good, but can such a smart pointer be implemented? </p>
<h2>Implementing arg::grin_ptr&lt;&gt; </h2>
<p>The principle problem to overcome in implementing <code>grin_ptr&lt;&gt;</code> is that the compiler generated copy constructor, assignment operator and destructor for <code>phone_list</code> will each instantiate the corresponding code for <code>grin_ptr&lt;&gt;</code> in a context where <code>implementation</code> is an incomplete type. </p>
<p>This means that the <code>grin_ptr&lt;&gt;</code> copy constructor cannot simply copy construct an instance of <code>implementation</code>. Likewise, the destructor of <code>grin_ptr&lt;&gt;</code> canâ€™t be a simple <code>delete p;</code> as deleting a pointer to an incomplete type gives undefined behaviour whenever the type in question has a non-trivial destructor. The assignment operator, will either have to deal with both these issues or delegate these problems. Letâ€™s write a test case for these operations: </p>
<pre><code>struct implementation; 
int implementation_instances = 0; 
int implementation_copies_made = 0; 

void test_incomplete_implementation(const arg::grin_ptr&lt;implementation&gt;&amp; const_grin) 
{ 
    assert(implementation_instances == 1); 
    assert(implementation_copies_made == 0);    
    { 
        // Check that copy construction works 
        // creates a new instance 

        arg::grin_ptr&lt;implementation&gt; nonconst_grin(const_grin); 

        assert(implementation_instances == 2); 
        assert(implementation_copies_made == 1); 

        // Check assignment calls copy constructor 
        // (and that the discarded implementation 
        // is deleted) 
        nonconst_grin = const_grin; 
        assert(implementation_instances == 2); 
        assert(implementation_copies_made == 2); 
    } 

    // Check destructor cleans up instances 
    assert(implementation_instances == 1); 
} 
</code></pre>

<p>Note that this test case is unable to initialise <code>grin_ptr&lt;&gt;</code> with an instance of <code>implementation</code> â€“ this is a direct consequence of <code>implementation</code> being an incomplete type. </p>
<p>In implementing <code>grin_ptr&lt;&gt;</code> I make use of the fact that the constructor is instantiated in the implementation file for <code>phone_list</code>, where the class definition for <code>implementation</code> resides. Similarly calls to <code>implementation</code> member functions also require a complete type. These are tested in the next part of the test harness: </p>
<pre><code>struct implementation 
{ 
    struct const_tag {}; 
    struct nonconst_tag {}; 

    const_tag function() const 
    { return const_tag(); } 

    nonconst_tag function() 
    { return nonconst_tag(); } 

    implementation() 
    { ++implementation_instances; } 

    implementation(const implementation&amp;) 
    { ++implementation_instances; 
    ++implementation_copies_made; } 

    ~implementation() 
    { --implementation_instances; } 
}; 

void test_implementation() 
{ 
    assert(implementation_instances == 0); 
    assert(implementation_copies_made == 0); 

    { 
        arg::grin_ptr&lt;implementation&gt; grin(new implementation); 
        assert(implementation_instances == 1); 
        assert(implementation_copies_made == 0); 

        test_incomplete_implementation(grin); 

        // Check that copy construction works 
        // creates a new instance 
        const arg::grin_ptr&lt;implementation&gt;&amp; const_grin(grin); 
        assert(implementation_instances == 1); 

        // if const qualification is wrong then 
        // these should produce compiler error 
        implementation::const_tag const_test = const_grin-&gt;function(); 
        implementation::nonconst_tag nonconst_test = grin-&gt;function(); 
    } 

    // Check destructor cleans up instance  
    assert(implementation_instances == 0); 
} 
</code></pre>

<p>If you examine the code for <code>grin_ptr&lt;&gt;</code> (shown in listing 1) youâ€™ll see that each instance carries around a pointer to a structure containing function pointers <code>do_copy</code> and <code>do_delete</code>. This structure is initialised using a trick I first saw used by Richard Hickey [6]: the constructor (which is instantiated with a complete type) instantiates the corresponding <code>my_delete_ftn</code> and <code>my_copy_ftn</code> template functions and stores the pointers to them. Because these see the full definition of the class used to initialise the pointer they can make use of its copy constructor and destructor (the casts are there to support implementation hierarchies). Using pointers to functions provides a safe method for <code>grin_ptr&lt;&gt;</code> to copy and 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 â€œby valueâ€ and no dynamic allocation is required. </p>
<p>There are few features that can be seen in this implementation that are not immediately related to the foregoing discussion: </p>
<ul>
<li>
<p>The dereference and indirection operators are const qualified, which allows the implementation class to overload on constin a natural manner. </p>
</li>
<li>
<p>The single argument (conversion) constructor may be initialised using a class derived from <code>implementation</code> â€“ this allows different specialisations of <code>implementation</code> to be selected at runtime<sup><a href="#fn:1">1</a></sup>. This functionality is illustrated in the test case given in Listing 2. </p>
</li>
<li>
<p>There is a two argument constructor that allows the user to provide custom copy and delete functionality. </p>
</li>
</ul>
<h2>Conclusion </h2>
<p>The class template presented here -<code>arg::grin_ptr&lt;&gt;</code> Â­removes some of the repetitive work required when implementing Cheshire Cat classes. In addition it is able to support applications that are considerably more sophisticated (making use of polymorphic implementations and/or overloading on const) than the <code>phone_list</code> example considered here. </p>
<p>Alan Griffiths<br>
<a href="mailto:alan@octopull.demon.co.uk">alan@octopull.demon.co.uk</a> </p>
<h2>References </h2>
<ol>
<li>
<p>â€œshared_ptr class templateâ€, Greg Colvin et al., http://www.boost.org/libs/smart_ptr/shared_ptr.htm </p>
</li>
<li>
<p>â€œEnding with the grinâ€, Alan Griffiths, http://www.octopull.demon.co.uk/arglib/TheGrin.html </p>
</li>
<li>
<p>â€˜Interpreting â€œSupporting the â€œCheshire Catâ€ idiomâ€â€™, Alan Griffiths &amp; Allan Newton, Overload 38 </p>
</li>
<li>
<p>â€œConstructing bullet-proof classesâ€, John Carolan, Proceedings: C++ at Work â€™89, SIGS </p>
</li>
<li>
<p>Design Patterns, Gamma, Helm, Johnson, Vlissides ISBN 0-201Â­63361-2, Addison-Wesley </p>
</li>
<li>
<p>Callbacks in C++ Using Template Functors, Richard Hickey C ++ Gems ISBN 1 884842 37 2 </p>
</li>
</ol>
<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">#ifndef INCLUDED_GRIN_PTR_HPP_ARG_20060308
#define INCLUDED_GRIN_PTR_HPP_ARG_20060308

#include &lt;utility&gt;
namespace arg
{
    template&lt;typename Grin&gt;
    class grin_ptr
    {
    public:
        /// Construct taking ownership of
        /// pointee.
        /// CheshireCat must be a complete type,
        /// Copyable and Destructable.

        template&lt;typename CheshireCat&gt;
        explicit grin_ptr(CheshireCat* pointee);

        /// Copy using copy function
        grin_ptr(const grin_ptr&amp; rhs);

        /// Destroy using delete function
        ~grin_ptr() throw()
        {
            copy_delete-&gt;do_delete(p);
        }

        /// Return contents (const)
        const Grin* get() const
        {
            return p;
        }

        /// Return contents (non-const)
        Grin* get()
        {
            return p;
        }

        /// Dereference op (const)
        const Grin* operator-&gt;()
        const
        {
            return p;
        }

        /// Dereference op (non-const)
        Grin* operator-&gt;()
        {
            return p;
        }

        /// Dereference op (const)
        const Grin&amp; operator*()
        const
        {
            return *p;
        }

        /// Dereference op (non-const)
        Grin&amp; operator*()
        {
            return *p;
        }

        /// Swaps contents with &quot;with&quot;
        void swap(grin_ptr&amp; with) throw();

        ///
        grin_ptr&amp; operator=(const grin_ptr&amp; rhs);

        /// Pointers to deep copy and delete
        /// functions
        struct copy_delete_ptrs
        {
            typedef void (*delete_ftn)(Grin*);
            typedef Grin* (*copy_ftn)(const Grin*);
            copy_ftn do_copy;
            delete_ftn do_delete;
        };

        /// Allow user to specify copy and delete
        grin_ptr(Grin* pointee, copy_delete_ptrs* cdp)
            : p(pointee), copy_delete(cdp) {}

    private:
        Grin* p;
        copy_delete_ptrs* copy_delete;

        template&lt;typename CheshireCat&gt;
        static void my_delete_ftn(Grin* p);

        template&lt;typename CheshireCat&gt;
        static Grin* my_copy_ftn(const Grin* p);
    };

    template&lt;typename Grin&gt;
    template&lt;typename CheshireCat&gt;
    inline void
    grin_ptr&lt;Grin&gt;::my_delete_ftn(Grin* p)
    {
        delete static_cast&lt;CheshireCat*&gt;(p);
    }

    template&lt;typename Grin&gt;
    template&lt;typename CheshireCat&gt;
    inline Grin*
    grin_ptr&lt;Grin&gt;::my_copy_ftn(const Grin* p)
    {
        return new CheshireCat(
                   static_cast&lt;const CheshireCat&amp;&gt;(*p));
    }

    template&lt;typename Grin&gt;
    template&lt;typename CheshireCat&gt;
    inline grin_ptr&lt;Grin&gt;::grin_ptr(CheshireCat* pointee)
        : p(pointee), copy_delete(0)
    {
        void(sizeof(CheshireCat));
        static copy_delete_ptrs cdp =
        {
            &amp;my_copy_ftn&lt;CheshireCat&gt;,
            &amp;my_delete_ftn&lt;CheshireCat&gt;
        };
        copy_delete = &amp;cdp;
    }

    template&lt;typename Grin&gt;
    inline void grin_ptr&lt;Grin&gt;::swap(grin_ptr&amp; with) throw()
    {
        std::swap(p, with.p);
        std::swap(copy_delete, with.copy_delete);
    }

    template&lt;typename Grin&gt;
    inline grin_ptr&lt;Grin&gt;::grin_ptr(const grin_ptr&amp; rhs)
        :
        p(rhs.copy_delete-&gt;do_copy(rhs.p)),
        copy_delete(rhs.copy_delete)
    {
    }

    template&lt;typename Grin&gt;
    inline grin_ptr&lt;Grin&gt;&amp;
    grin_ptr&lt;Grin&gt;::operator=(const grin_ptr&amp; rhs)
    {
        grin_ptr&lt;Grin&gt;(rhs).swap(*this);
        return *this;
    }
}

namespace std
{
    template&lt;class Grin&gt;
    inline void swap(
        ::arg::grin_ptr&lt;Grin&gt;&amp; lhs,
        ::arg::grin_ptr&lt;Grin&gt;&amp; rhs) throw()
    {
        lhs.swap(rhs);
    }
}
#endif
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 1 â€“ grin_ptr.hpp</td>
</tr>
</table>

<table class="sidebartable">
<tr>
<td>
<pre class="programlisting">struct base
{
protected:
    base() {}
    base(const base&amp;) {}
};

struct derived1 : base
{
    static int instances;

    derived1()  { ++instances; }    
    derived1(const derived1&amp; src)
    : base(src) { ++instances; }
    ~derived1() { --instances; }
};

int derived1::instances = 0;

struct derived2 : base
{
    static int instances;

    derived2()  { ++instances; }
    derived2(const derived2&amp; src)
    : base(src) { ++instances; }
    ~derived2() { --instances; }
};

int derived2::instances = 0;

void test_derived()
{
    assert(derived1::instances == 0);
    assert(derived2::instances == 0);

    {
        arg::grin_ptr&lt;base&gt; d1(new derived1);
        arg::grin_ptr&lt;base&gt; d2(new derived2);

        assert(derived1::instances == 1);
        assert(derived2::instances == 1);
        {
            // Check that copy works
            arg::grin_ptr&lt;base&gt; d(d1);
            assert(derived1::instances == 2);
            assert(derived2::instances == 1);

            // Check assignment from d1
            d = d1;
            assert(derived1::instances == 2);
            assert(derived2::instances == 1);

            // Check assignment from d2
            d = d2;
            assert(derived1::instances == 1);
            assert(derived2::instances == 2);
        }

        // Check destruction
        assert(derived1::instances == 1);
        assert(derived2::instances == 1);
    }

    // Check destruction
    assert(derived1::instances == 0);
    assert(derived2::instances == 0);
}
</pre>
</td>
</tr>
<tr>
<td class="title">Listing 2 â€“ test for polymorphic implementation</td>
</tr>
</table>

<div class="footnotes">
<hr>
<ol>
<li id="fn:1">
<p>This is a difference from the earlier implementation of <code>grin_ptr</code> â€“ in that, if the user wanted to derive from <code>implementation</code>, it was necessary for implementation to derive from <code>arg::cloneable</code> and to declare the destructor virtual. I feel the current approach is more natural and extensible. &nbsp;<a href="#fnref:1" rev="footnote">â†©</a></p>
</li>
</ol>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
