    <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  :: All Heap No Leaks</title>
        <link>https://members.accu.org/index.php/articles/306</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 #60 - Apr 2004</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/c152/">60</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+152/">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;All Heap No Leaks</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 April 2004 22:54:59 +01:00 or Fri, 02 April 2004 22:54:59 +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>The use of new and delete in C++ can cause problems for both
novice and expert developers alike. Using new without a
corresponding delete results in a memory leak. Some languages such
as C#, Java and Python provide managed objects that can be created
on the managed heap leaving deletion to the garbage collector.</p>
<p>Smart pointers allow similar behaviour to be achieved in C++,
with the added bonus that they provide deterministic destruction of
the object to which they point. However, the user still has to know
that they should be using smart pointers and many don't. In this
article I am going to look at a way of writing C++ objects that can
only be created on the heap, and that must be managed by (memory
management) smart pointers.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id="d0e24"></a>Creating
Objects on the Heap</h2>
</div>
<p>There are a number of situations in which it makes sense to
force objects to be created on the heap. I recently developed a
thin database access layer for use with my cross-platform test
framework [<a href="#Aeryn">Aeryn</a>]. The sole purpose of the
layer is to allow databases to be created and dropped before and
after tests. Although Open Database Connectivity (ODBC) is
available on both Windows and Linux (my initial target platforms),
I decided to allow the use of ActiveX Data Objects (ADO) on Windows
as it sometimes provides better performance.</p>
<p>ODBC and ADO are very different. ODBC is implemented as a C
based API and ADO is implemented as a family of COM objects.
However, both use a connection string to connect to a database and
allow the execution of strings containing SQL statements. Therefore
both types of database connection can be used via a common abstract
base class.</p>
<p>Like many other types of resources a database connection is
expensive and the most expensive operation is generally the initial
connection to the database. In an ideal situation an application
would have a single database connection object that is shared by
all of the objects in the application that require database access.
Connection to the database would be put off until absolutely
necessary (lazy evaluation), and maintained for as long as
possible. This results in the connection being created in one part
of the application and (potentially) destroyed in another.</p>
<p>A common interface to one or more concrete objects, and the
lifetime requirements of a database connection object, make it an
ideal candidate for heap creation. One of the most likely scenarios
is that the appropriate database connection object would be created
at the highest possible level via a Factory Method [<a href=
"#Gamma-">Gamma-</a>] that takes the connection string as a
parameter. The database connection object is then passed to objects
in the application that need to use it [<a href=
"#Gamma-">Gamma-</a>], via a reference counted smart pointer
[<a href="#Henney2">Henney2</a>]). The first object to attempt to
execute a SQL statement causes a connection to the database to be
made, and then the connection is maintained throughout the lifetime
of the database connection object.</p>
<p>As the database connection object is created via a factory
method, it follows that it should be destroyed via a Disposal
Method [<a href="#Henney3">Henney3</a>]. The disposal method can be
passed to the reference counted smart pointer and used to destroy
the database connection object instead of delete. This is an
example of the Resource Acquisition Is Initialisation [<a href=
"#Henney4">Henney4</a>] idiom provided by smart pointers.</p>
<p>The use of factory and disposal methods gives the writer of the
database connection object complete control over how and where the
object is created.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e57" id="d0e57"></a>Background</h2>
</div>
<p>In Item 27 of More Effective C++ [<a href="#Meyers">Meyers</a>]
Scott Meyers discusses ways of restricting objects so that they can
only be created on the heap. Meyers explains that sometimes a
developer wants to create objects that can destroy themselves by
calling delete this. If an attempt was made to create such an
object on the stack the effects could be catastrophic, so it makes
sense to enforce heap creation.</p>
<p>Equally there are times when a developer wants to prevent an
object from being created on the heap. For example local (or
automatic) variables are unlikely to require heap creation. Meyers
also discusses preventing objects from being created on the heap.
This can be achieved by declaring <tt class="literal">operator
new</tt> and <tt class="literal">operator new[]</tt> private.
Meyers also suggests that unless there is a compelling reason not
to, <tt class="literal">operator delete</tt> and <tt class=
"literal">operator delete[]</tt> should also be made private.</p>
<pre class="programlisting">
namespace Meyers {
  class NotOnHeap {
  private:
    static void* operator new(size_t);
    static void operator delete(void*);
    static void* operator new[](size_t);
    static void operator delete[](void*);
  };
}
</pre>
<p>Meyers forces heap-only creation by making the object's
destructor private (or protected if you want to be able to inherit
from the object) and implementing a disposal method. For
example:</p>
<pre class="programlisting">
namespace Meyers {
  class HeapOnly {
  private:
    ~HeapOnly() {}
  public:
    // Disposal Method
    void Destroy() { delete this; }
  };
}
</pre>
<p>If an attempt is made to create this object on the stack:</p>
<pre class="programlisting">
int main() {
  using namespace Meyers;
  HeapOnly heapOnly;
}
</pre>
<p>the compiler will issue an error. However, if the object is
created on the heap:</p>
<pre class="programlisting">
int main() {
  using namespace Meyers;
  HeapOnly* pHeapOnly = new HeapOnly;
  pHeapOnly-&gt;Destroy();
}
</pre>
<p>the compiler is perfectly happy (gcc 3.2.3 [<a href=
"#gcc">gcc</a>] issues a warning about <tt class=
"classname">HeapOnly</tt> only having a private destructor and no
friends).</p>
<p>In terms of forcing objects to be created on the heap, Meyers's
example does exactly what is needed. However, it does have one
drawback. The developer using the heap-only object must explicitly
call <tt class="methodname">Destroy</tt> in order to prevent a
memory leak. Wouldn't it be better if when the pointer pointing to
the heap-only object went out of scope it destroyed the object
automatically? After all that is what this article is about! Enter
smart pointers!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e106" id="d0e106"></a>Managing
Heap-Only Objects with Smart Pointers</h2>
</div>
<p>With the exception of developing this managed heap-only object,
I don't remember the last time I explicitly used the <tt class=
"literal">delete</tt> keyword. Every time I create an object on the
heap I use a smart pointer to prevent a memory leak. Generally, I
use Boost's [<a href="#boost">boost</a>] <tt class=
"classname">scoped_ptr</tt> and <tt class=
"classname">shared_ptr</tt>, although there are other smart
pointers available, including the reference counted smart pointer
described by Meyers at the end of More Effective C++ [<a href=
"#Meyers">Meyers</a>].</p>
<p>So what happens if <tt class="classname">shared_ptr</tt> is used
with Meyers's heaponly object?</p>
<pre class="programlisting">
int main() {
  using namespace Meyers;
  boost::shared_ptr&lt;HeapOnly&gt; pHeapOnly(new HeapOnly);
}
</pre>
<p>The compiler reports an error because <tt class=
"classname">shared_ptr</tt> cannot call <tt class=
"classname">HeapOnly</tt>'s private destructor. Herb Sutter
discusses some ways of getting around this in his CUJ [<a href=
"#cuj">cuj</a>] article Befriending Templates [<a href=
"#Sutter">Sutter</a>]. However, I prefer a different approach
suggested by an <tt class="literal">accu-general</tt> regular,
James Slaughter, which requires some changes to Meyers's <tt class=
"classname">HeapOnly</tt> object.</p>
<p>So, let's start with a new object, a managed object rather than
a heap-only object:</p>
<pre class="programlisting">
class Managed {
private:
  ~Managed() {}
public:
  static void Destroy(Managed* pManaged) {
    delete pManaged;
  }
};
</pre>
<p><tt class="classname">shared_ptr</tt> can take a second
constructor argument, which is a function pointer used to destroy
the object. To accommodate this, the managed object's <tt class=
"methodname">Destroy</tt> member function is now static and has a
single parameter which is a pointer to the managed object. The
pointer is used to delete the object instead of <tt class=
"literal">delete this</tt>. The lifetime of the managed object can
now be fully managed by the shared pointer like this:</p>
<pre class="programlisting">
int main() {
  boost::shared_ptr&lt; Managed &gt; pManaged(new Managed, Managed::Destroy);
}
</pre>
<p>The above syntax isn't as nice as it could be and the developer
using the managed object must still make a conscious decision to
use the smart pointer and must also know that <tt class=
"classname">shared_ptr</tt>'s constructor can take a second
parameter. Wouldn't it be better if the developer could only use
the smart pointer? Some would argue that restricting a developer is
bad. I agree in a lot of instances, but not this one, when the aim
is to have a heap-based managed object that cannot leak memory.</p>
<p>So, how can a developer be forced to use a smart pointer? The
answer is to make all the managed object's constructors, including
the copy-constructor, private (or protected if the you want to
inherit from the object) and provide a static factory method that
returns a smart pointer (obviously if the managed object has a
number of different constructors then a factory method that takes
the appropriate parameters must be added for each):</p>
<pre class="programlisting">
class Managed {
public:
  typedef boost::shared_ptr&lt; Managed &gt; SmartPtr;
  // Factory Method
  static SmartPtr Create() {
    return SmartPtr(new Managed, Destroy);
  }
private:
  Managed() {}
  ~Managed() {}
  // Disposal Method
  static void Destroy(Managed* pManaged) {
    delete pManaged;
  }
  Managed(const Managed&amp;);
};
</pre>
<p>An instance of the managed object can then be created in the
following way:</p>
<pre class="programlisting">
int main() {
  Managed::SmartPtr pManaged = Managed::Create();
}
</pre>
<p>Although we now have a managed C++ object, the solution still
isn't as versatile as it could be. What if the developer using the
managed object is not able to use Boost (possibly for some
commercial reason) or would like to use a custom smart pointer or a
smart pointer that offers thread safety? Any type of memory
management smart pointer can be used with the managed object, as
long as it supports assignment and can take a disposal method as a
second constructor parameter. The introduction of a template
template parameter [<a href="#Vandervoorde-">Vandervoorde-</a>]
allows smart pointers to be interchanged easily.</p>
<pre class="programlisting">
template&lt; template&lt; class &gt; class SmartPtrT &gt;
class Managed {
public:
  typedef SmartPtrT&lt; Managed &gt; SmartPtr;
  static SmartPtr Create() {
    return SmartPtr(new Managed, Destroy);
  }
private:
  Managed() {}
  ~Managed() {}
  static void Destroy(Managed* pManaged) {
    delete pManaged;
  }
  Managed(const Managed&amp;);
};
</pre>
<p>The syntax used to create the parameterised managed object can
be simplified by introducing a typedef:</p>
<pre class="programlisting">
int main() {
  typedef Managed&lt; boost::shared_ptr &gt; Managed;
  Managed::SmartPtr pManaged = Managed::Create();
}
</pre>
<p>Ok, so now we have a managed object that can be used with
different smart pointers. However, this solution requires a lot of
extra code to be added to each new managed class written. Let's
have a look at some boilerplate code that can be used to simplify
the conversion of regular objects into managed objects.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e195" id="d0e195"></a>Managed
Object Boilerplate Code</h2>
</div>
<p>First we need a regular object to convert to a managed object.
An abstract base class pointer usually points to an object created
on the heap. Therefore in this example I am going to use the simple
class hierarchy that the thin database access layer described above
provides, as it consists of an interface class with a single pure
virtual member function, and a concrete class that implements the
base class's member function:</p>
<pre class="programlisting">
class IConnection {
public:
  virtual ~IConnection() {}
public:
  virtual void ExecuteSQL(const std::string&amp; sql) = 0;
};

class Connection : public IConnection {
public:
  explicit Connection(const std::string&amp; connectionString) {
    std::cout &lt;&lt; &quot;Connection String: &quot;
              &lt;&lt; connectionString &lt;&lt; &quot;\n&quot;;
  }
  virtual ~Connection() {
    std::cout &lt;&lt; &quot;Disconnecting\n&quot;;
  }
  virtual void ExecuteSQL(const std::string&amp; sql) {
    std::cout &lt;&lt; &quot;Execute: &quot; &lt;&lt; sql &lt;&lt; &quot;\n&quot;;
  }
};
</pre>
<p><tt class="classname">IConnection</tt> cannot be created on the
stack or the heap, as it has a pure virtual member function.
Connection can be created on the stack or the heap, as it has the
compiler generated default public constructor and destructor (see
item 45 of Scott Meyers' Effective C++ [<a href=
"#Meyers2">Meyers2</a>]), and no pure virtual member functions.</p>
<p>For <tt class="classname">Connection</tt> to be fully managed it
must be prohibited from being created on the stack or on the heap,
other than via a factory method. Preventing heap creation is easy,
as discussed above; all that needs to be done is to define private
or protected implementations of <tt class="literal">operator
new</tt> and <tt class="literal">operator new[]</tt>. The factory
method can then use these implementations to create an instance of
<tt class="classname">Connection</tt> on the heap.</p>
<p>There are two ways of preventing <tt class=
"classname">Connection</tt> from being created on the stack: As
discussed above, it can be given private or protected constructors
and destructors or a pure virtual member function.</p>
<p>As the intention is to create boilerplate code <tt class=
"classname">Connection</tt> itself should be modified as little as
possible. Inheriting from a managed base class is a simple way of
adding (and documenting) managed behaviour. The following
<tt class="classname">ManagedBase</tt> class defines a protected
<tt class="literal">operator new</tt> and <tt class=
"literal">operator new[]</tt> (with their corresponding <tt class=
"literal">delete</tt> operators), disposal method, virtual
destructor to ensure proper deletion, and pure virtual member
function:</p>
<pre class="programlisting">
class ManagedBase {
private:
  template&lt; typename ConcreteT, typename InterfaceT,
            template&lt; class &gt; class SmartPtrT &gt;
  friend class Managed;
  class OnlyAvailableToManaged {};
  virtual void ForceUseOfManaged (const OnlyAvailableToManaged&amp;) const = 0;
  template&lt; template&lt; class &gt; class SmartPtrT,
            class InterfacePtrT,
            class ConcretePtrT,
            class ConcreteTypeT &gt;
  friend class SmartPtrPolicyTraits;
protected:
  virtual ~ManagedBase() {}
  static void Destroy(const ManagedBase* pManagedBase) {
    delete pManagedBase;
  }
  static void* operator new(size_t size) {
    return ::operator new(size);
  }
  static void operator delete(void *pObject) {
    ::operator delete(pObject);
  }
  static void* operator new[](size_t size) {
    return ::operator new[](size);
  }
  static void operator delete[](void *pObject) {
    ::operator delete[](pObject);
  }
};
</pre>
<p>In practice there is nothing to stop the creator of <tt class=
"classname">Connection</tt> from declaring its constructors and
destructors public, and therefore negating that method of
preventing stack creation. If a pure virtual member function is
used, which in its simplest form would have a return value of void
and exactly zero parameters, the creator of <tt class=
"classname">Connection</tt> could allow stack creation by
overriding it and giving it a body.</p>
<p>One solution to the problem presented by using a pure virtual
member function to prevent stack creation was suggested in a
private email from Mikael Kilpelainen. If the pure virtual member
function (<tt class="methodname">ForceUseOfManaged</tt>) has a
parameter (<i class=
"parameter"><tt>OnlyAvailableToManaged</tt></i>) of a type that is
private to the class in which the pure virtual member function is
declared, it is possible to restrict the classes that can override
the pure virtual member function to friends of the class in which
it is declared.</p>
<p>Therefore, the only way that the creator of <tt class=
"classname">Connection</tt> can override the pure virtual member
function declared in <tt class="classname">ManagedBase</tt> is to
make <tt class="classname">Connection</tt> a friend of <tt class=
"classname">ManagedBase</tt>. This cannot be done without modifying
<tt class="classname">ManagedBase</tt>. The knock-on effect is that
another class must be provided that derives from <tt class=
"classname">Connection</tt> and is a friend of <tt class=
"classname">ManagedBase</tt>. This class is discussed next.</p>
<p><tt class="classname">ManagedBase</tt> lacks the necessary
factory method. Although it is possible for a base class to create
an instance of its subclass [<a href="#Henney5">Henney5</a>] a
factory method is not present in <tt class=
"classname">ManagedBase</tt>. The factory method is a member of
another class, <tt class="classname">Managed</tt>:</p>
<pre class="programlisting">
template&lt; typename ConcreteT,
          typename InterfaceT,
          template&lt; class &gt; class SmartPtrT &gt;
class Managed : private ConcreteT {
public:
  typedef SmartPtrT&lt;InterfaceT&gt; InterfacePtr;
  typedef SmartPtrT&lt;ConcreteT&gt; ConcretePtr;
private:
  ~Managed() {}
public:
  static InterfacePtr Create() {
    return SmartPtrPolicyTraits&lt; SmartPtrT,
                                 InterfacePtr,
                                 ConcretePtr,
                                 ConcreteT &gt;
    ::Initialise(new Managed);
  }
};
</pre>
<p><tt class="classname">Managed</tt> has a private destructor to
prevent stack creation. As <tt class="classname">Managed</tt>'s
factory method will create an instance of <tt class=
"classname">Connection</tt> (<tt class="classname">ConcreteT</tt>)
and return a smart pointer (<tt class="classname">SmartPtrT</tt>)
of type <tt class="classname">IConnection</tt> (<tt class=
"classname">InterfaceT</tt>), all three must be specified as
template parameters.</p>
<p>Managed inherits from <tt class="classname">ConcreteT</tt> so
that it can override and define a body for the pure virtual
function (<tt class="methodname">ForceUseOfManaged</tt>) defined in
<tt class="classname">ManagedBase</tt>. The smart pointers for the
types <tt class="classname">ConcreteT</tt> and <tt class=
"classname">InterfaceT</tt> are typedef'd for convenience.</p>
<p>The factory method (<tt class="methodname">Create</tt>) uses
traits [<a href="#Myers">Myers</a>] &amp; [<a href=
"#Vandervoorde-">Vandervoorde-</a>] to enable initialisation code
for different smart pointers to be added easily. The factory method
creates an instance of <tt class="classname">Managed</tt> on the
heap, and passes a pointer to it to the trait Initialise function.
The Initialise function returns a copy of the initialised smart
pointer, which is then returned by the factory method.</p>
<p>When calling the trait <tt class="methodname">Initialise</tt>
function the smart pointer type must be specified so that the
compiler knows which trait to use. The interface type and concrete
smart pointer type and the concrete type must also be specified as
these are used by the <tt class="methodname">Initialise</tt>
function. The traits template is defined as follows:</p>
<pre class="programlisting">
template&lt; template&lt; class &gt; class SmartPtrT,
          class InterfacePtrT,
          class ConcretePtrT,
          class ConcreteTypeT &gt;
class SmartPtrPolicyTraits;
</pre>
<p>A partial specialisation [<a href=
"#Vandervoorde-">Vandervoorde-</a>] is used to define the way in
which Boost's <tt class="classname">smart_ptr</tt> is
initialised:</p>
<pre class="programlisting">
template&lt; class InterfacePtrT,
          class ConcretePtrT,
          class ConcreteTypeT &gt;
class SmartPtrPolicyTraits&lt; boost::shared_ptr,
                            InterfacePtrT,
                            ConcretePtrT,
                            ConcreteTypeT &gt; {
public:
  static InterfacePtrT Initialise(ConcreteTypeT* pConcrete) {
    return ConcretePtrT(pConcrete, &amp;ManagedBase::Destroy);
  }
};
</pre>
<p><tt class="methodname">Initialise</tt> needs to be able to
access <tt class="methodname">Destroy</tt>, the protected static
member function defined in <tt class="classname">ManagedBase</tt>.
One way to allow this would be to make <tt class=
"methodname">Destroy</tt> public, but then it could be called from
anywhere. <tt class="methodname">Destroy</tt> should only be called
by the specified smart pointer. The alternative solution is to
declare <tt class="classname">SmartPtrPolicyTraits</tt> a friend of
<tt class="classname">ManagedBase</tt>. The required friend
template is shown in the definition of <tt class=
"classname">ManagedBase</tt> above, but here it is again:</p>
<pre class="programlisting">
class ManagedBase {
protected:
template&lt; template&lt; class &gt; class SmartPtrT,
          class InterfacePtrT,
          class ConcretePtrT,
          class ConcreteTypeT &gt;
  friend class SmartPtrPolicyTraits;
  ...
};
</pre>
<p>All the boilerplate code is now in place. In order to make
<tt class="classname">Connection</tt> a managed object it must be
modified to inherit from <tt class=
"classname">ManagedBase</tt>:</p>
<pre class="programlisting">
class Connection : public ManagedBase,
                   public IConnection {
public:
  explicit Connection(const std::string&amp; connectionString) {
    std::cout &lt;&lt; &quot;Connection String: &quot;
              &lt;&lt; connectionString &lt;&lt; &quot;\n&quot;;
  }
  ...
};
</pre>
<p>There is still one outstanding problem. <tt class=
"classname">Connection</tt>'s constructor takes a single argument
and <tt class="classname">Managed</tt> does not have the
appropriate constructor or factory method. There are at least two
possible solutions to this problem; each has its advantages and
disadvantages.</p>
<p>The first is to create a partial template specialisation of
<tt class="classname">Managed</tt> specifically for <tt class=
"classname">Connection</tt>, which has the appropriate constructor
and factory method:</p>
<pre class="programlisting">
template&lt; typename InterfaceT,
          template&lt; class &gt; class SmartPtrT &gt;
class Managed&lt; Connection,
               InterfaceT,
               SmartPtrT &gt;
         : private Connection {
public:
  typedef SmartPtrT&lt;InterfaceT&gt; InterfacePtr;
  typedef SmartPtrT&lt;Connection&gt; ConcretePtr;
private:
  explicit Managed(const std::string&amp; connectionString)
        : Connection(connectionString) {}
  ~Managed() {}
public:
  static InterfacePtr Create(const std::string&amp; connectionString) {
    return SmartPtrPolicyTraits&lt; SmartPtrT,
                                 InterfacePtr,
                                 ConcretePtr,
                                 Connection &gt;
             ::Initialise(new Managed(connectionString));
  }
};
</pre>
<p>The advantage with this solution is that you can control how the
constructor parameter is passed to <tt class=
"methodname">Create</tt> and on to <tt class=
"classname">Managed</tt>'s constructor. For example, if for some
reason <tt class="classname">Connection</tt> modified <i class=
"parameter"><tt>connectionString</tt></i>, the partial template
specialisation allows the parameter to be specified as and passed
by (non-const) reference. The disadvantage of this solution is that
it is a lot of extra code, as it is effectively a reimplementation
of <tt class="classname">Managed</tt>.</p>
<p>The second solution is to give <tt class=
"classname">Managed</tt> a number of templated constructors and
<tt class="methodname">create</tt> function pairs. For example:</p>
<pre class="programlisting">
template&lt; typename ConcreteT,
          typename InterfaceT,
          template&lt; class &gt; class SmartPtrT &gt;
class Managed : private ConcreteT {
  ...
private:
  explicit Managed() : ConcreteT() {}

  template&lt; typename A &gt;
  explicit Managed(const A&amp; a)
      : ConcreteT(a) {}

  template&lt; typename A, typename B &gt;
  explicit Managed(const A&amp; a, const B&amp; b)
      : ConcreteT(a, b) {}

  ...

public:
  static InterfacePtr Create() {
    return SmartPtrPolicyTraits&lt; SmartPtrT,
                                 InterfacePtr,
                                 ConcretePtr,
                                 ConcreteT &gt;
               ::Initialise(new Managed);
  }

  template&lt; typename A &gt;
  static InterfacePtr Create(const A&amp; a) {
    return SmartPtrPolicyTraits&lt; SmartPtrT,
                                 InterfacePtr,
                                 ConcretePtr,
                                 ConcreteT &gt;
               ::Initialise(new Managed(a));
    }

  template&lt; typename A, typename B &gt;
  static InterfacePtr Create(const A&amp; a, const B&amp; b) {
    return SmartPtrPolicyTraits&lt; SmartPtrT,
                                 InterfacePtr,
                                 ConcretePtr,
                                 ConcreteT &gt;
               ::Initialise(new Managed(a, b));
  }
};
</pre>
<p>The advantage is that extra code is not needed for objects that
have different numbers of constructor parameters, assuming that
none of the objects have a number of constructor parameters greater
than the constructor and <tt class="methodname">Create</tt> pair
with the highest number of parameters. The disadvantages are that
you cannot control how the parameters are passed to <tt class=
"methodname">Create</tt> and onto the constructor, as you can by
using the partial template specialisation and that you cannot use
an object that has more constructor parameters than the constructor
and <tt class="methodname">Create</tt> pair with the highest number
of parameters unless you modify <tt class="classname">Managed</tt>.
There is, however, a workaround for the second disadvantage using
the boost [<a href="#boost">boost</a>] <tt class=
"literal">PreProcessor</tt> library, shown to me by Paul
Mensonides:</p>
<pre class="programlisting">
#include &lt;boost/preprocessor/arithmetic/inc.hpp&gt;
#include &lt;boost/preprocessor/repetition/enum_binary_params.hpp&gt;
#include &lt;boost/preprocessor/repetition/enum_params.hpp&gt;
#include &lt;boost/preprocessor/repetition/repeat.hpp&gt;

#ifndef MAX_ARITY
#define MAX_ARITY 1
#endif

template&lt; typename ConcreteT,
          typename InterfaceT,
          template&lt; class &gt; class SmartPtrT &gt;
class Managed : private ConcreteT {
public:
  typedef SmartPtrT&lt;InterfaceT&gt; InterfacePtr;
  typedef SmartPtrT&lt;ConcreteT&gt; ConcretePtr;
private:
  explicit Managed() : ConcreteT() {}

#define CTOR( z, n, _) \
  template&lt; BOOST_PP_ENUM_PARAMS( \
            BOOST_PP_INC(n), typename A) &gt; \
  explicit Managed(BOOST_PP_ENUM_BINARY_PARAMS \
                   (BOOST_PP_INC(n), \
                   const A, &amp; p)) \
             : ConcreteT(BOOST_PP_ENUM_PARAMS( \
                         BOOST_PP_INC(n), p)) {} \
    /**/
    BOOST_PP_REPEAT(MAX_ARITY, CTOR, ~)
#undef CTOR

  virtual ~Managed() {}
  virtual void ForceUseOfManaged(const
       ManagedBase::OnlyAvailableToManaged&amp;)
       const {}
public:
  static InterfacePtr Create() {
    return SmartPtrPolicyTraits&lt; SmartPtrT,
                                 InterfacePtr,
                                 ConcretePtr,
                                 ConcreteT &gt;
               ::Initialise(new Managed);
  }

#define CREATE(z, n,) \
  template&lt; BOOST_PP_ENUM_PARAMS( \
            BOOST_PP_INC(n), typename A) &gt; \
  static InterfacePtr \
  Create(BOOST_PP_ENUM_BINARY_PARAMS( \
         BOOST_PP_INC(n), \
         const A, &amp;p)) { \
    return SmartPtrPolicyTraits&lt; SmartPtrT, \
                                 InterfacePtr, \
                                 ConcretePtr, \
                                 ConcreteT &gt; \
             ::Initialise(new \
                 Managed(BOOST_PP_ENUM_PARAMS( \
                         BOOST_PP_INC(n), p))); \
  } \
  /**/
  BOOST_PP_REPEAT(MAX_ARITY, CREATE, ~)
#undef CREATE
};
</pre>
<p>The above code tells the C++ pre-processor to generate
<tt class="literal">MAX_ARITY</tt> constructor and Create function
pairs. For more information on exactly how it does this, consult
the boost <tt class="literal">PreProcessor</tt> library
documentation on the Boost [<a href="#boost">boost</a>]
website.</p>
<p>There is no need to choose between either the constructor and
<tt class="methodname">Create</tt> function pairs solution or the
partial template specialisation solution. Both solutions coexist
quite happily together. The compiler will choose the partial
template specialisation solution over the templated constructor and
<tt class="methodname">Create</tt> function pairs solution.
Therefore you should use the templated constructor and <tt class=
"methodname">Create</tt> function pairs solution by default, when
the constructor parameters of your object are passed by const
reference and write a partial template specialisation when your
object requires constructor parameters to be passed by something
other than const.</p>
<p>Finally we are at the stage where instances of our managed
object can be created. The syntax used to create a managed object
can be greatly simplified using another typedef:</p>
<pre class="programlisting">
int main() {
  typedef Managed&lt; Connection,
                   IConnection,
                   boost::shared_ptr &gt;
          ManagedConnection;
  ManagedConnection::InterfacePtr
      pConnection = ManagedConnection::Create(
                       &quot;Connection String&quot;);
      pConnection-&gt;ExecuteSQL(
                       &quot;SELECT * FROM MyTable&quot;);
}
</pre>
<p>Now that we have our managed object, we should check that it
behaves in the way we expect. We have already seen that it can be
created on the heap via the factory method; let's see if it can be
created on the heap using <tt class="literal">new</tt>:</p>
<pre class="programlisting">
int main() {
  typedef Managed&lt; Connection,
                   IConnection,
                   boost::shared_ptr &gt;
          ManagedConnection;
  ManagedConnection::InterfacePtr
    pConnection
      = new ManagedConnection(
              &quot;Connection String&quot;);
  ...
}
</pre>
<p>No. The compiler gives an error stating that it cannot access
<tt class="literal">operator new</tt> and <tt class=
"literal">operator delete</tt> in <tt class=
"classname">ManagedConnection</tt> as they are private. So far so
good; What about creating the managed object on the stack:</p>
<pre class="programlisting">
int main() {
  typedef Managed&lt; Connection,
                   IConnection,
                   boost::shared_ptr &gt;
          ManagedConnection;
  ManagedConnection connection(
          &quot;Connection String&quot;);
}
</pre>
<p>No, this doesn't work either. The compiler gives an error,
stating that it cannot access the private constructor and
destructor in <tt class="classname">ManagedConnection</tt>. Ok,
what about creating the Connection object directly on the heap:</p>
<pre class="programlisting">
int main() {
  IConnection* pIConnection =
         new Connection(&quot;Connection String&quot;);
}
</pre>
<p>No, this doesn't work. The compiler complains that it cannot
instantiate <tt class="classname">Connection</tt> as it is an
abstract class and that it cannot access <tt class=
"classname">Connection</tt>'s <tt class="literal">new</tt> and
<tt class="filename">delete</tt> operators as they are private.
What about creating <tt class="classname">Connection</tt> directly
on the stack?</p>
<pre class="programlisting">
int main() {
  Connection
      connection(&quot;Connection String&quot;);
}
</pre>
<p>This final test doesn't work either. The compiler complains that
it cannot create <tt class="classname">Connection</tt> as it is an
abstract class. Making <tt class="classname">Connection</tt> static
or a class member does not work either, for the same reason.</p>
<p>These five tests demonstrate that our managed object works as
expected.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e560" id="d0e560"></a>Finally</h2>
</div>
<p>In this article I have discussed how to use smart pointers to
prevent memory leaks and ways of forcing objects to be created on
the heap only, while also preventing the possibility of a memory
leak.</p>
<p>I expect this technique to be useful not only to library writers
but also to general application writers who are concerned about
possible misuse of their objects by other people.</p>
<p>I also hope this will appeal as a viable alternative to people
thinking about Microsoft's Managed C++ as a solution to their
memory leak problems.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e569" id=
"d0e569"></a>Acknowledgments</h2>
</div>
<p>Thanks to: James Slaughter, Adrian Fagg, Phil Nash, Mark
Radford, Kevlin Henney, Allan Kelly, Mikael Kilpelainen, Jennifer
Hart, Paul Mensonides, Tim Pushman</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e574" id="d0e574"></a>References:</h2>
</div>
<div class="bibliomixed"><a name="Aeryn" id="Aeryn"></a>
<p class="bibliomixed">[Aeryn] Aeryn: <span class=
"bibliomisc"><a href="http://www.paulgrenyer.co.uk/aeryn/" target=
"_top">http://www.paulgrenyer.co.uk/aeryn/</a></span></p>
</div>
<div class="bibliomixed"><a name="Gamma-" id="Gamma-"></a>
<p class="bibliomixed">[Gamma-] <span class="citetitle"><i class=
"citetitle">Design Patterns: elements of reusable object-oriented
software</i></span> , Erich Gamma, Richard Helm, Ralph Johnson,
John Vlissides, Addison Wesley, ISBN 0201633612</p>
</div>
<div class="bibliomixed"><a name="Henney1" id="Henney1"></a>
<p class="bibliomixed">[Henney1] The method of creating objects at
the highest level and then passing some form of reference around
has come to be known in some circles as Parameterise from Above and
is a much talked about work in progress by Kevlin Henney:
<span class="bibliomisc"><a href=
"http://www.java.no/web/moter/javazone03/presentations/KevlinHenney/Programmer_s%20Dozen.pdf"
target=
"_top">http://www.java.no/web/moter/javazone03/presentations/KevlinHenney/Programmer_s%20Dozen.pdf</a></span></p>
</div>
<div class="bibliomixed"><a name="Henney2" id="Henney2"></a>
<p class="bibliomixed">[Henney2] <span class="citetitle"><i class=
"citetitle">Reference Counting</i></span>, Kevlin Henney:
<span class="bibliomisc"><a href=
"http://www.two-sdg.demon.co.uk/curbralan/papers/europlop/ReferenceAccounting.pdf"
target=
"_top">http://www.two-sdg.demon.co.uk/curbralan/papers/europlop/ReferenceAccounting.pdf</a></span></p>
</div>
<div class="bibliomixed"><a name="Henney3" id="Henney3"></a>
<p class="bibliomixed">[Henney3] <span class="citetitle"><i class=
"citetitle">Factory and Disposal Methods</i></span>, Kevlin Henney:
<span class="bibliomisc"><a href=
"http://www.two-sdg.demon.co.uk/curbralan/papers/vikingplop/FactoryAndDisposalMethods.pdf"
target=
"_top">http://www.two-sdg.demon.co.uk/curbralan/papers/vikingplop/FactoryAndDisposalMethods.pdf</a></span></p>
</div>
<div class="bibliomixed"><a name="Henney4" id="Henney4"></a>
<p class="bibliomixed">[Henney4] <span class="citetitle"><i class=
"citetitle">Executing Around Sequences</i></span>, Kevlin Henney:
<span class="bibliomisc"><a href=
"http://www.two-sdg.demon.co.uk/curbralan/papers/europlop/ExecutingAroundSequences.pdf"
target=
"_top">http://www.two-sdg.demon.co.uk/curbralan/papers/europlop/ExecutingAroundSequences.pdf</a></span></p>
</div>
<div class="bibliomixed"><a name="Meyers" id="Meyers"></a>
<p class="bibliomixed">[Meyers] <span class="citetitle"><i class=
"citetitle">More Effective C++</i></span>, Scott Meyers, Addison
Wesley, ISBN 020163371X</p>
</div>
<div class="bibliomixed"><a name="gcc" id="gcc"></a>
<p class="bibliomixed">[gcc] gcc 3.2.3: <span class=
"bibliomisc"><a href="http://gcc.gnu.org/" target=
"_top">http://gcc.gnu.org/</a></span></p>
</div>
<div class="bibliomixed"><a name="boost" id="boost"></a>
<p class="bibliomixed">[boost] Boost: <span class=
"bibliomisc"><a href="http://www.boost.org/" target=
"_top">www.boost.org/</a></span></p>
</div>
<div class="bibliomixed"><a name="cuj" id="cuj"></a>
<p class="bibliomixed">[cuj] CUJ: <span class="bibliomisc"><a href=
"http://www.cuj.com/" target=
"_top">http://www.cuj.com/</a></span></p>
</div>
<div class="bibliomixed"><a name="Myers" id="Myers"></a>
<p class="bibliomixed">[Myers] <span class="citetitle"><i class=
"citetitle">Traits: a new and useful template technique</i></span>,
Nathan C. Myers: <span class="bibliomisc"><a href=
"http://www.cantrip.org/traits.html" target=
"_top">http://www.cantrip.org/traits.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Vandervoorde-" id=
"Vandervoorde-"></a>
<p class="bibliomixed">[Vandervoorde-] <span class=
"citetitle"><i class="citetitle">C++ Templates: The Complete
Guide</i></span>, David Vandervoorde, Nicolai M. Josuttis, Addison
Wesley, ISBN 0201734842</p>
</div>
<div class="bibliomixed"><a name="Sutter" id="Sutter"></a>
<p class="bibliomixed">[Sutter] <span class="citetitle"><i class=
"citetitle">Befriending Templates</i></span>, Herb Sutter,
<span class="bibliomisc"><a href=
"http://www.cuj.com/documents/s=8244/cujcexp2101sutter/" target=
"_top">http://www.cuj.com/documents/s=8244/cujcexp2101sutter/</a></span></p>
</div>
<div class="bibliomixed"><a name="Meyers2" id="Meyers2"></a>
<p class="bibliomixed">[Meyers2] <span class="citetitle"><i class=
"citetitle">Effective C++: 50 Specific Ways to Improve Your
Programs and Designs</i></span>, Scott Meyers, Addison Wesley, ISBN
0201924889</p>
</div>
<div class="bibliomixed"><a name="Henney5" id="Henney5"></a>
<p class="bibliomixed">[Henney5] <span class="citetitle"><i class=
"citetitle">Data Abstraction and Heterarchy</i></span>, Kevlin
Henney, <span class="bibliomisc"><a href=
"http://www.cuj.com/documents/s=7992/cujcexp1908henney/" target=
"_top">http://www.cuj.com/documents/s=7992/cujcexp1908henney/</a></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
