    <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  :: Shallow Pointer</title>
        <link>https://members.accu.org/index.php/articles/587</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">Design of applications and programs + Overload Journal #28 - Oct 1998</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/c67/">Design</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/c175/">28</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c67+175/">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;Shallow Pointer</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 27 October 1999 18:23:02 +01:00 or Wed, 27 October 1999 18:23:02 +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>Recently I read Francis' excellent 'Exploring Patterns' article
in Overload [<a href="#OL27">OL27</a>] and his 'The object of STL
containers' in [<a href="#EXE">EXE</a>]. I thought I should share
some of my own experience in this area.</p>
<p>During the design and implementation phases of my last project,
a requirement emerged for STL containers of pointers to objects. We
could not use value based objects, since the objects were complex,
and smart pointers or an STL allocator did not appear to offer the
solution either.</p>
<p>The following problem and solution description is not a Pattern,
but I'm reusing the form provided by the GOF book [<a href=
"#GoF">GoF</a>] as a framework.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e35" id="d0e35"></a>Intent</h2>
</div>
<p>This class allows an STL container to manage a set of objects,
the design of which dictates that their life-time has to be managed
in a special way which is different from the STL's by-value
semantics. This design introduces an implicit contract with the
Client that they must manage the life-time of the Objects.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e40" id="d0e40"></a>Motivation</h2>
</div>
<p>In the project there were several (three or four) instances
where a 'Manager' class had a set of objects. The life-time of the
objects was such that they could not be copied without considerable
design and run-time cost. These objects were typically resource
hungry, often with a life-time of their own because. they created
threads or processes for their own internal use. Copies were hard
to create, if it was just to move the object in memory, especially
where resources were mutexes, which by definition are for granting
exclusivity to another resource. Also temporary copies are a
complete anathema to the object as they may cause resource
scheduling which would absorb lots of CPU time.</p>
<p>A Smart or Reference Counted pointer might not work in these
circumstances because the object could not be copied and there
would only be one of each Object anyway.</p>
<p>An STL allocator could not be used as it just wants to create
and manage memory and does not know when a new object is needed
versus a copy of an old one.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e49" id=
"d0e49"></a>Applicability</h2>
</div>
<p>This solution is applicable when:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>an STL container provides the required semantics for the
containment of the Objects</p>
</li>
<li>
<p>the cost of creating copies of the an object is large</p>
</li>
<li>
<p>the implementation of either a Smart Pointer or an Allocator for
the STL list would not solve the issues</p>
</li>
<li>
<p>Creation of the Object can be done at the same time as it is
added to the Container</p>
</li>
<li>
<p>Destruction of the Object can be done at the same time as it is
removed from the Container</p>
</li>
<li>
<p>The creation and destruction of the Object can be done from one
function each within the Manager.</p>
</li>
<li>
<p>The Object has a complex set of parameters required to define
its initial state.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e76" id="d0e76"></a>Structure</h2>
</div>
<div class="c2"><img src="/var/uploads/journals/resources/Ridout%20structure.png" align=
"middle"></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e81" id=
"d0e81"></a>Participants</h2>
</div>
<p><span class="bold"><b>Manager:</b></span> This class includes an
attribute of type:</p>
<pre class="programlisting">
           &lt;list &lt;ShallowPointer&lt; Object &gt; &gt;
</pre>
<p>This class is responsible for the memory management of the
Objects, specifically, it must create 'new' objects to add to the
container and 'delete' them off the container.</p>
<p><span class="bold"><b>Shallow Pointer:</b></span> This is a
template class that simply:</p>
<div class="orderedlist">
<ol type="a">
<li>
<p>dereferences the Object for the Manager</p>
</li>
<li>
<p>forwards ('==' &amp; '&lt;' from the STL to the Object)</p>
</li>
</ol>
</div>
<p>It does <span class="bold"><b>not</b></span> perform any memory
or life-time management.</p>
<p><span class="bold"><b>Object:</b></span> This has to provide the
operators required by the STL container, which are forwarded by the
ShallowPointer template class. It abdicates responsibility for its
life-time management to the Manager.</p>
<p><span class="bold"><b>ObjectParam:</b></span> The Parameters
required to instantiate an Object. This helps but is not a
mandatory part of this design. This also confers the added property
of enforcing non-implicit type conversions for the creation of
Objects, See [<a href="#Meyers">Meyers</a>] 'Item 5'.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e119" id=
"d0e119"></a>Collaborations</h2>
</div>
<p>It is the Manager that has to manage the life-time of the
Objects. The Manager needs to create new instances of Objects as
they are added onto the list and is required to delete the Objects
as they are removed from the list. This is best achieved by having
one 'AddObject' and one 'DelObject' function in the Manager, with
these being the <span class="bold"><b>only</b></span> places where
the list is added to or has Objects removed from it. This is the
implicit contract between the ShallowPointer and its Client.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e127" id=
"d0e127"></a>Consequences</h2>
</div>
<p>The life-time of the object is tightly coupled with its tenure
in the Container. This is an undesirable side-effect for which this
design is very unattractive. Also the management of the Object is
in the hands of the Client rather than being hidden from the
Client, another unattractive feature of this design.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e132" id=
"d0e132"></a>Implementation</h2>
</div>
<pre class="programlisting">
I have put the bodies into the class definition, but in the source code there are separate header and implementation files.
template &lt;class T&gt;
class ShallowPointer {
public:
  ShallowPointer(T *pObj)
    : pObject(pObj) {} ;
  ShallowPointer(
               const ShallowPointer &amp;rhs)
  {
  // Shallow Copy
        pObject = rhs.GetPointer();
  }

  ~ShallowPointer() throw() {
    pObject = 0 ; // Shallow Delete
  }

  // De-reference this Pointer to return
  // a pointer to the Object of type T as
  // a T *const - this should be private?
  T *const GetPointer() const
  { return pObject ; } 

  // De-reference this Pointer to return 
  // a pointer to the Object of type T as
  // a T *const. Thus providing 
  // 'transparent' access to members of T
  // from the List without adding them to
  // this class.
  T *const operator -&gt;() const
  { return GetPointer() ; } 
  T *const operator *() const
  { return GetPointer() ; } 

  // Used by List::sort(), Forward to
  // Object
  int operator &lt;(
            const ShallowPointer &amp;rhs) 
  {
   return GetPointer()-&gt;
          operator&lt;(*rhs.GetPointer()) ;
  }

  // Used by List::, Forward to Object
  int operator ==(
               const ShallowPointer &amp;rhs)
 {
    return GetPointer()-&gt;
          operator==(*rhs.GetPointer()) ;
  }

private: 
  // Hide from Compiler, STL &amp; Clients   
  ShallowPointer();
  const ShallowPointer&lt;T&gt; &amp; 
     operator=(
         const ShallowPointer&lt;T&gt; &amp;right);

private:
  // Attributes
  T *pObject ; // Pointer to our Object
};
</pre>
<pre class="programlisting">
// The required operations in Manager::
// Construct &amp; add to the Container based 
// on a set of parameters
void Manager::AddObject( ObjectParam op ) {
  queue.push_back( new Object(op) ) ;

  // post-condition: list is in
  // priority order
  queue.sort() ;
}

// Find and removed the specified Object 
// from the Conainer &amp; destruct the 
// Object
void Manager::DelObject(
                    Object *const pObj ) 
{
list&lt;ShallowPointer&lt;Object&gt; &gt;::iterator i;
  for( i = queue.begin(); 
       i != queue.end(); i++ )
  {
    if( (*i).GetPointer == pObj ) 
    { // Compare Pointers not Objects
      // Remove from Container
      queue.erase( i ) ;
      delete pObj ;
      break ;
    }
  }
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e139" id="d0e139"></a>Sample Client
Code</h2>
</div>
<p>This sample code, relies on there being two member functions in
Object:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>bool Object::IsCal() const ;</p>
</li>
<li>
<p>void Object::StartJob() ; // not const!!!</p>
</li>
</ol>
</div>
<p>It uses the first function to choose an Object of interest and
then uses the second to send a message to the Object.</p>
<pre class="programlisting">
Object *const Manager::StartCalibration()
{
  // pre-condition:
  // list is in priority order
  queue.sort() ;

  Object *pJob(0) ;

  list&lt;ShallowPointer&lt;Object&gt; &gt;::const_iterator i ;
  for( i = queue.begin(); 
       i != queue.end(); i++ )
  {
    if( !pJob &amp;&amp; (*i)-&gt;IsCal() )
    {
    // Find the highest priority cal. Job
    // Keep Pointer [see limitations]
    pJob = *i.GetPointer() ;
    break ;
    }
  }

  if( pJob )
  {
     // Start the Process
     pJob-&gt;StartJob() ;
  }

  return pJob ;
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e155" id="d0e155"></a>Known
Uses</h2>
</div>
<p>In this project the prime use was that of a Queue Manager (the
Manager class), which was required to maintain an ordered list of
Jobs (the Object class). Each Job had a Priority and a Function.
The Priority was higher for Jobs submitted by Acquisition and lower
for Jobs submitted by the User (for re- processing). Job Functions
were: Calibration, Legacy or Signal Processing (User defined from
supplied building blocks). It was decided to use an STL list and
use the sort member function to provide the required 'ordering'.
Each Job had to manage the resources required to execute its
process. This was achieved by having a thread per Job to manage its
state machine and a process per job for the actual processing. Unix
Signals and Process Control functions were used to synchronise and
manage the Jobs, with messages and call-backs to the Queue Manager
to keep the Manager informed. The Queue Manager was
single-threaded, so STL access was simple.</p>
<p>The reason an STL list was used rather than an STL vector, was
simply that someone had defined the STL list in Rational Rose and
none of the other containers!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e162" id=
"d0e162"></a>Limitations</h2>
</div>
<p>ShallowPointer::GetPointer() should be private, having it in
public scope exposes the fact that internally this class is
managing a pointer. We should also being hiding this implementation
detail.</p>
<p>What I think this solution lacks is controlled, and hidden,
object lifetime management. This design is too ad-hoc to leave it
to STL and the Client of the Object (Manager). What I think is
required is another class to control the life-time management of
the Objects, similar to a Factory perhaps, but then the Factory may
have to become the container too, and provide the required iterator
classes too.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e169" id="d0e169"></a>Summary</h2>
</div>
<p>This is a very lightweight implementation and as I write this, I
can see increasingly that Francis is correct in asserting that a
'Smart Pointer' approach may be the correct way forward. See:
[<a href="#OL27">OL27</a>] 'Exploring Patterns' and [<a href=
"#EXE">EXE</a>] 'The Object of STL Containers'. This solution needs
to be extended to incorporate more of the semantics of the Smart
Pointer.</p>
<p>As Kevlin amusingly observed at the excellent ACCU Forum 98, if
you have two choices always pick the third. In this case, our
choices are By-Value and Smart Pointers, so we should pick the
ShallowPointer solution. This may be the worst of both worlds as it
lacks the simplicity of the STL's by-value semantics and does not
provide the controlled management of a Smart Pointer.</p>
<p>This solution may only be half-baked, but it has worked
successfully for us. It was expedient at the time and has the
merits of being simple enough to be tested and trusted, although it
does place a high burden on the Client to use. This is probably too
high a price. As Scott Meyers observes in <a href=
"#Meyers">Meyers</a> the job of the class designer should be hard
(and it wasn't in this case) so that the role of the Client is
simple (it isn't in this case). Thus I can only conclude that this
is a bad design and should be taken as an example of such.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e187" id="d0e187"></a>References</h2>
</div>
<div class="bibliomixed"><a name="GoF" id="GoF"></a>
<p class="bibliomixed">[GoF] '<span class="citetitle"><i class=
"citetitle">Design Patters</i></span>'; Gamma, Helm, Johnson,
Vlissides; Addison-Wesley; 0-201-63361-2</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; 0-201-63371-X</p>
</div>
<div class="bibliomixed"><a name="OL27" id="OL27"></a>
<p class="bibliomixed">[OL27] '<span class="citetitle"><i class=
"citetitle">Overload 27</i></span>'; ACCU; 1354-3172</p>
</div>
<div class="bibliomixed"><a name="EXE" id="EXE"></a>
<p class="bibliomixed">[EXE] '<span class="citetitle"><i class=
"citetitle">.EXE</i></span> Volume 13 Issue 3 August 1997'; Centaur
Communications Ltd; 0268-6872</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
