    <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  :: Two-thirds of a Pimpl and a Grin</title>
        <link>https://members.accu.org/index.php/articles/302</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 #70 - Dec 2005</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/c142/">70</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+142/">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;Two-thirds of a Pimpl and a Grin</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 December 2005 05:00:00 +00:00 or Fri, 02 December 2005 05:00:00 +00: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>This article describes an easy method to reduce compilation
dependencies and build times. This method would not be interesting
enough to warrant an article on it, except that it is the key to an
interesting method of managing project-wide objects, and I have not
seen this method mentioned anywhere.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a>Background</h2>
</div>
<p>While watching another religious war starting to erupt over the
use of Singletons, I realized that I had not seen the method I use
discussed anywhere else, including The Code Project [<a href=
"#CodeProject">CodeProject</a>]. It has some advantages to it, and,
as I haven't seen it mentioned, I figured I'd post it. (Of course,
having said that, I'll probably come across an article on the exact
same thing tomorrow.)</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id="d0e30"></a>The Method</h2>
</div>
<p>The method itself, as I said, is not very interesting. Simply
use smart pointers to hold all non-POD objects stored in your class
interface.</p>
<p>Well, there is one interesting thing about it - you cannot use
<tt class="classname">auto_ptr</tt>'s or many other smart pointers
in order to store your objects if you don't include at least an
empty destructor inside the unit's <tt class="filename">.cpp</tt>
file. That is the reason the following uses Alan Griffiths'
<tt class="classname">grin_ptr</tt> [<a href=
"#Griffiths">Griffiths</a>]. You could also use <tt class=
"classname">boost::shared_ptr</tt>, and probably some others that I
am unaware of.</p>
<p>The reason that you can't use an <tt class=
"classname">auto_ptr</tt> for this purpose is simply that
<tt class="classname">auto_ptr</tt> must have a complete definition
of the forward declared class at the point of destruction, and if
you rely upon the default destructor, the forward declaration of
the class is the only thing the <tt class="classname">auto_ptr</tt>
has, so it will generate a 'do-nothing' default destructor for the
class being held. This is rarely, if ever, what you want.</p>
<p>(If you are unsure whether a smart pointer can be used for this
purpose without creating a destructor in the holding class's
<tt class="filename">.cpp</tt> file, look in the smart pointer's
documentation for a statement saying something to the effect that
it can hold and correctly destroy an incomplete type. If it says
that, you can safely use it without having to remember to supply a
destructor in the <tt class="filename">.cpp</tt> file.)</p>
<p>As a quick example of the pattern I am talking about, here is a
theoretical implementation of my wallet:</p>
<pre class="programlisting">
//Header file, include guards not shown
#include &quot;arg.h&quot;
//Only uses forward declarations:
class CreditCard;
class BusinessCard;
class DollarBill;
class Wallet {
private:
  // Make it simple - just one of each
  arg::grin_ptr&lt;CreditCard&gt; masterCardC;
  arg::grin_ptr&lt;BusinessCard&gt; businessCardC;
  arg::grin_ptr&lt;DollarBill&gt; dollarBillC;
  // anything else, but if they are classes, 
  // wrap them in pointers as above.
public:
  Wallet();
  BusinessCard &amp; businessCard() 
    { return *businessCardC.get(); }
  // I really don't want to 
  // expose the following two,
  // but this is simply an example...
  CreditCard &amp; masterCard() 
    { return *masterCardC.get(); }
  DollarBill &amp; dollarBill() 
    { return *dollarBillC.get(); }
  // anything else...
};

//Implementation file
#include &quot;Wallet.h&quot;
#include &quot;CreditCard.h&quot;
#include &quot;BusinessCard.h&quot;
#include &quot;DollarBill.h&quot;
Wallet::Wallet() :
  masterCardC(new MasterCard(/*any args*/)),
  businessCardC(new BusinessCard(/*any args*/)),
  dollarBillC(new DollarBill()) { }
// And anything else...
</pre>
<p>(Feel free to 'new' me some more dollar bills. :) )</p>
<p>Anyway, as you can see, nothing to get excited over, until you
think about it for a second. We have just entirely eliminated all
external dependencies except the <tt class="filename">arg.h</tt>
file from the <tt class="classname">Wallet</tt> header. If the
implementation to <tt class="classname">CreditCard</tt>, <tt class=
"classname">BusinessCard</tt>, or <tt class=
"classname">DollarBill</tt> changes, the only units that need to be
recompiled in the project are the <tt class="classname">Wallet</tt>
unit and the unit that you changed. This is a big saving over
having 'hard objects' in the class's header file. In that case,
every unit that <tt class="literal">#include</tt>d <tt class=
"filename">Wallet.h</tt> would be recompiled anytime the
implementation to <tt class="classname">CreditCard</tt>, <tt class=
"classname">BusinessCard</tt>, or <tt class=
"classname">DollarBill</tt> changed.</p>
<p>The saving with the above method is not as good as a full pimpl
implementation, as a full pimpl implementation enables you to
recompile <tt class="classname">CreditCard</tt>, <tt class=
"classname">BusinessCard</tt>, or <tt class=
"classname">DollarBill</tt>, without the <tt class=
"classname">Wallet</tt> unit or any other unit in the project
needing to be recompiled. (Of course, changing the interface to a
pimpl can be a PITA, and will require more to be recompiled at that
time.)</p>
<p>The method I have just outlined is simpler than the pimpl
pattern, as it does not require you to create an intermediary
<tt class="classname">PimplHolder</tt> class. You do, however, have
to use <tt class="literal">-&gt;</tt> notation to access all of the
smart pointer held objects from within the class they are held in,
unless you create a local reference to them within the function
using them.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e134" id="d0e134"></a>The
'Interesting Use'</h2>
</div>
<p>The above method can be used to easily manage project-wide
objects. This method, when used in a global, can quite often be
used as a quasi-Singleton manager. Doing so will often simplify
some aspects of your overall design, and it will do so without
increasing compilation dependencies.</p>
<p>Please do not take this to mean that I don't like Singletons.
The pattern I am about to show you does not replace Singletons.
There is nothing in this pattern to keep you from instantiating
multiple copies of the objects held in this container. This pattern
simply makes it very easy to manage and use project-wide objects,
and it may be an appealing alternative if you do not really care to
mess with figuring your way around Singleton instantiation order
dependencies.</p>
<p>Also, do not take this to mean that I am a huge proponent of
globals. This pattern allows me to minimize the use of globals to
two or three for my entire project, and I am happy with that. I do
store quite a few variables within the global objects, though, and
as these variables are defined within the header file of the
global, whenever their interface changes, or I add another item to
the global, every unit that <tt class="literal">#includes
&quot;Globals.h&quot;</tt> will be recompiled at that time. If your project
takes considerable time for a rebuild of such a nature, you will
want to carefully atomize your globals, maybe even to the point of
making each object (like <tt class="classname">TextureManager</tt>
in the following code) into its own global item. I outline a
wrapper that will simplify this for you in the addendum at the end
of this article.</p>
<p>Let me give a simple example of this 'interesting use'. The two
changes to the previous example that are needed are to change it so
that it holds things commonly held in Singletons, and make the
class into a global. The example I gave while the religious war was
raging was the following:</p>
<pre class="programlisting">
// Header file (minus include guards again)
#include &quot;arg.h&quot;
class TextureManager;
class LoggingSystem;
class ObjectManager;
// ...
class Globals {
private:
  arg::grin_ptr&lt;TextureManager&gt; textureManagerC;
  arg::grin_ptr&lt;LoggingSystem&gt; loggerC;
  arg::grin_ptr&lt;ObjectManager&gt; objectManagerC;
  // ...
public:
  Globals();
  TextureManager &amp; textureManager() 
    { return *textureManagerC.get(); }
  LoggingSystem  &amp; logger()         
    { return *loggerC.get(); }
  ObjectManager  &amp; objectManager()  
    { return *objectManagerC.get(); }
  // ...
};
// Implementation file:
#include &quot;TextureManager.h&quot;
#include &quot;LoggingSystem.h&quot;
#include &quot;ObjectManager.h&quot;
Globals::Globals() :
  textureManagerC(new TextureManager()),
  loggerC(new LoggingSystem()),
  objectManagerC(new ObjectManager())
  /* and any other stuff */ { }
// Here is a sample of a 'main' file:
#include &quot;Globals.h&quot;
Globals gGlobals;
// The following #include is only 
// so we can access 'doSomething'.
// We don't need it for the global creation.
#include &quot;TextureManager.h&quot;
int main() {
  gGlobals.textureManager().doSomething();
  //...
  return 0;
}
</pre>
<p>And that is it, although if you need to pass in initialization
parameters, in order to pass them to one of your classes, you will
need to implement <tt class="varname">gGlobals</tt> as a pointer,
and initialize it after whatever parameter it is dependant upon is
obtained. The best option is to implement it through the use of an
<tt class="classname">auto_ptr</tt> (in which case <tt class=
"classname">auto_ptr</tt> has no problems):</p>
<pre class="programlisting">
Globals * gGlobals;
int main() {
  // Do whatever in order to get your 'args'
  // ... and finally
  std::auto_ptr&lt;Globals&gt; tGlobals(
     new Globals(/*args*/));
  gGlobals = tGlobals.get();
  //...
}
</pre>
<p>Using the method outlined above, you can explicitly control your
object creation order, and very easily overcome the issues that
arise when trying to control multiple Singletons with
inter-singleton creation order dependencies. In addition, this
method has a simpler syntax than Singletons. Singletons require
something like:</p>
<pre class="programlisting">
SingletonManager::getInstance().
   textureManager().doSomething()
</pre>
<p>in order to use them from a Singleton manager. The above method
boils down to:</p>
<pre class="programlisting">
gGlobals.textureManager().doSomething()
</pre>
<p>But the truly interesting part is that using this technique, if
you only modify the <tt class="filename">TextureManager.cpp</tt>
file, it will be the only file recompiled at recompilation. If you
modify the <tt class="filename">TextureManager.h</tt> file, only
units that explicitly <tt class="literal">#include
&quot;TextureManager.h&quot;</tt> will be recompiled. This will include the
<tt class="classname">Globals</tt> unit, but will not include every
file that <tt class="literal">#includes &quot;Globals.h&quot;</tt>.</p>
<p>It is worth reading the last paragraph again, and looking at the
code, until you understand that this system is not exposing any of
the other objects being managed by the <tt class=
"classname">Globals</tt> unit to any unit that is not <tt class=
"literal">#include</tt>-ing the sub-unit you wish access to. You
can <tt class="literal">#include &quot;Globals.h&quot;</tt> in every
<tt class="filename">.cpp</tt> file in your program, but they won't
link to <tt class="classname">TextureManager</tt> until you
explicitly <tt class="literal">#include &quot;TextureManager.h&quot;</tt> as
well as <tt class="filename">Globals.h</tt> in the unit you want to
access the <tt class="classname">TextureManager</tt> from. There
are no other compilation dependencies to be aware of, and the
<tt class="classname">Globals</tt> unit does not impose any more
overhead than a few forward declarations, the class declaration of
<tt class="classname">Globals</tt> itself, and a few bits for the
<tt class="classname">grin_ptr</tt>'s internals.</p>
<p>The secrets to this whole technique: using only forward
declarations and a capable smart pointer.</p>
<p>I hope that you find this technique useful, and wish you happy
coding.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e230" id="d0e230"></a>Addendum</h2>
</div>
<p>If you do atomize your globals, and do not wish to use
Singletons, you can modify the previous method to instantiate your
globals within main, and completely control your instantiation and
destruction order:</p>
<pre class="programlisting">
Globals * gGlobals;
TextureManager * gTextureMan;
// ...
int main() {
  std::auto_ptr&lt;Globals&gt; tGlobals(
     new Globals(/*args*/));
  gGlobals = tGlobals.get();
  std::auto_ptr&lt;TextureManager&gt;
     tTextureMan(new TextureManager());
  gTextureMan = tTextureMan.get();
  // And, if you want, you can even destroy 
  // them in any order. Just manually call 
  // 'release' on the pointers in the order 
  // you want at the end of 'main', rather
  // than relying upon the auto_ptr's 
  // destructors.
}
</pre>
<p>You could even create a class to manage these atomized globals.
Doing so would overcome the previous objection to long build times.
I envision something of the following nature:</p>
<pre class="programlisting">
// GlobalManager.h w/o include guards
class TextureManager;
class OtherGlobals;
class GlobalManager {
private:
  arg::grin_ptr&lt;TextureManager&gt;
     textureManagerC;
  arg::grin_ptr&lt;OtherGlobals&gt; otherGlobalsC;
  //...
};
//GlobalManager.cpp
#include &quot;TextureManager.h&quot;
TextureManager * gTextureMan;
#include &quot;OtherGlobals.h&quot;
OtherGlobals * gOtherGlobals;
GlobalManager::GlobalManager() {
  textureManagerC.reset(new TextureManager());
  gTextureMan = textureManagerC.get();
  otherGlobalsC.reset(new OtherGlobals());
  gOtherGlobals = otherGlobalsC.get();
  // ...
}
//Main unit:
#include &quot;GlobalManager.h&quot;
int main() {
  // Automatically instantiate all 
  // globals in one fell swoop:
  std::auto_ptr&lt;GlobalManager&gt; 
     globals(new GlobalManager());
  // ...
}
</pre>
<p>Using this method, all of your globals will automatically be
instantiated for you in a manner that only forces your main unit to
recompile if you add more globals. You no longer have the 'hiding'
that took place in the earlier pattern I discussed, but you have a
simple method of controlling your global class instantiation order.
You can even explicitly control the destruction order, if you
desire, by creating a destructor for the global organizer class,
and calling 'release' upon the smart pointers in the order you want
the objects to be released.</p>
<p>Hopefully, the above discussion has given you more options when
it comes to implementing global objects. As always, use what works
for you, and keep the religious wars to a minimum :)</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e245" id="d0e245"></a>References</h2>
</div>
<div class="bibliomixed"><a name="CodeProject" id=
"CodeProject"></a>
<p class="bibliomixed">[CodeProject] The Code Project, <span class=
"bibliomisc"><a href="http://www.codeproject.com/" target=
"_top">http://www.codeproject.com/</a></span></p>
</div>
<div class="bibliomixed"><a name="Griffiths" id="Griffiths"></a>
<p class="bibliomixed">[Griffiths] Alan Griffiths, 1999, Ending
with the Grin, <span class="bibliomisc"><a href=
"http://www.octopull.demon.co.uk/arglib/TheGrin.html" target=
"_top">http://www.octopull.demon.co.uk/arglib/TheGrin.html</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>
