    <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  :: &quot;Here be Dragons&quot;</title>
        <link>https://members.accu.org/index.php/articles/298</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;&quot;Here be Dragons&quot;</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>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;The use of animals in maps was commonplace from the earliest
times. Man's deepest fears and superstitions concerning wide
expanses of uncharted seas and vast tracts of 'terra incognita'
were reflected in the monstrous animals that have appeared on maps
ever since the Mappa Mundi.&quot; (Roderick Barron in &quot;Decorative
Maps&quot;)</p>
</blockquote>
</div>
<p>For many developers C++ exception handling is like this - a Dark
Continent with poor maps and rumours of ferocious beasts. I'm Alan
Griffiths and I'm your guide to the landmarks and fauna of this
region.</p>
<p>In order to discuss exception safety we need to cover a lot of
territory. The next section identifies the &quot;exception safe&quot;
mountains in the distance. Please don't skip it in the hope of
getting to the good stuff - if you don't take the time to get your
bearings now you'll end up in the wastelands.</p>
<p>Once I've established the bearings I'll show you a well-trodden
path that leads straight towards the highest peak and straight
through a tar pit. From experience, I've concluded that everyone
has to go down this way once. So I'll go with you to make sure you
come back. Not everyone comes back; some give up on the journey,
others press on deeper and deeper into the tar pit until they sink
from sight.</p>
<p>On our journey I'll tell you the history of how the experts
sought for a long time before they discovered a route that bypasses
that tar pit and other obstacles. Most maps don't show it yet, but
I'll show you the signs to look out for. I'll also show you that
the beasts are friendly and how to enlist their aid.</p>
<p>If you look into the distance you'll see a range of peaks, these
are the heights of exception safety and are our final destination.
But before we proceed on our trek let me point out two of the most
important of these peaks, we'll be using them as landmarks on our
travels&hellip;</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e33" id="d0e33"></a>The Mountains
(Landmarks of Exception Safety)</h2>
</div>
<p>The difficulty in writing exception safe code isn't in writing
the code that throws an exception, or in writing the code that
catches the exception to handle it. There are many sources that
cover these basics. I'm going to address the greater challenge of
writing the code that lies in between the two.</p>
<p>Imagine for a moment the call stack of a running program,
function <tt class="function">a()</tt> has called function
b<tt class="function">()</tt>, <tt class="function">b()</tt> has
called <tt class="function">c()</tt>, and so on, until we reach
<tt class="function">x()</tt>; <tt class="function">x()</tt>
encounters a problem and throws an exception. This exception causes
the stack to unwind, deleting automatic variables along the way,
until the exception is caught and dealt with by <tt class=
"function">a()</tt>.</p>
<p>I'm not going to spend any time on how to write functions
<tt class="function">a()</tt> or <tt class="function">x()</tt>. I'm
sure that the author of <tt class="function">x()</tt> has a
perfectly good reason for throwing an exception (running out of
memory, disc storage, or whatever) and that the author of
<tt class="function">a()</tt> knows just what to do about it
(display: &quot;Sorry, please upgrade your computer and try
again!&quot;).</p>
<p>The difficult problem is to write all the intervening functions
in a way that ensures that something sensible happens as a result
of this process. If we can achieve this we have &quot;exception safe&quot;
code. Of course, that begs the question &quot;what is 'something
sensible'?&quot; To answer this let us consider a typical function
<tt class="function">f()</tt> in the middle of the call stack. How
should <tt class="function">f()</tt> behave?</p>
<p>Well, if <tt class="function">f()</tt> were to handle the
exception it might be reasonable for it to complete its task by
another method (a different algorithm, or returning a &quot;failed&quot;
status code). However, we are assuming the exception won't be
handled until we reach <tt class="function">a()</tt>. Since
<tt class="function">f()</tt> doesn't run to completion we might
reasonably expect that:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><tt class="function">f()</tt> doesn't complete its task.</p>
</li>
<li>
<p>If <tt class="function">f()</tt> has opened a file, acquired a
lock on a mutex, or, more generally; if <tt class=
"function">f()</tt> has &quot;allocated a resource&quot; then the resource
should not leak. (The file must be closed, the mutex must be
unlocked, etc.)</p>
</li>
<li>
<p>If <tt class="function">f()</tt> changes a data structure, then
that structure should remain useable - e.g. no dangling
pointers.</p>
</li>
</ol>
</div>
<p>In summary: If <tt class="function">f()</tt> updates the system
state, then the state must remain valid. Note that isn't quite the
same as correct - for example, part of an address may have changed
leaving a valid address object containing an incorrect address.</p>
<p>I'm going to call these conditions the basic exception safety
guarantee, this is the first, and smaller of our landmark
mountains. Take a good look at it so that you'll recognise it
later.</p>
<p>The basic exception safety guarantee may seem daunting but not
only will we reach this in our travels, we will be reaching an even
higher peak called the strong exception safety guarantee that
places a more demanding constraint on <tt class=
"function">f()</tt>:</p>
<div class="orderedlist">
<ol start="4" type="1">
<li>
<p>If <tt class="function">f()</tt> terminates by propagating an
exception then it has made no change to the state of the
program.</p>
</li>
</ol>
</div>
<p>Note that it is impossible to implement <tt class=
"function">f()</tt> to deliver either the basic or strong exception
safety guarantees if the behaviour in the presence of exceptions of
the functions it calls isn't known. This is particularly relevant
when the client of <tt class="function">f()</tt> (that is
<tt class="function">e()</tt>) supplies the functions to be called
either as callbacks, as implementations of virtual member
functions, or via template parameters. In such cases the only
recourse is to document the constraints on them - as, for example,
the standard library does for types supplied as template parameters
to the containers.</p>
<div class="sidebar">
<p class="title c3">Destructors That Throw Exceptions</p>
<p>Exceptions propagating from destructors cause a number of
problems. For example, consider a <tt class="classname">Whole</tt>
that holds pointers to a <tt class="classname">PartOne</tt>, a
<tt class="classname">PartTwo</tt>, and a <tt class=
"classname">PartThree</tt> that it owns (ie it must delete them).
If the destructors of the parts propagate exceptions, we would have
trouble just writing a destructor for <tt class=
"classname">Whole</tt>. If more than one destructor throws, we must
suppress at least one exception while remembering to destroy the
third part. Writing update methods (like assignment) under such
circumstances is prohibitively difficult or impossible.</p>
<p>There many situations where an exception propagating from a
destructor is extremely inconvenient - my advice is not to allow
classes that behave in this manner into your system. (If forced to,
you can always 'wrap' them in a well behaved class of your
own.)</p>
<p>If you look at the standard library containers, you'll find that
they place certain requirements on the types that are supplied as
template parameters. One of these is that the destructor doesn't
throw exceptions. There is a good reason for this: it is hard to
write code that manipulates objects that throw exceptions when you
try to destroy them. In many cases, it is impossible to write
efficient code under such circumstances.</p>
<p>In addition, the C++ exception handling mechanism itself objects
to destructors propagating exception during the &quot;stack unwinding&quot;
process. Indeed, unless the application developer takes
extraordinary precautions the application will be terminated in a
graceless manner.</p>
<p>There is no advantage in allowing destructors to propagate
exceptions and a whole host of disadvantages. It should be easy to
achieve: in most cases all a destructor should be doing is
destroying other objects whose destructors shouldn't throw, or
releasing resources - and if that fails an exception won't
help.</p>
<p>Apart from the practicalities what does an exception from a
destructor mean? If I try to destroy an object and this fails what
am I supposed to do? Try again?</p>
<p>Destructors that throw exceptions? Just say no.</p>
</div>
<p>If we assume a design with fully encapsulated data then each
function need only be held directly responsible for aspects of the
object of which it is a member. For the rest, the code in each
function must rely on the functions it calls to behave as
documented. (We have to rely on documentation in this case, since
in C++ there is no way to express these constraints in the
code.)</p>
<p>We'll rest here a while, and I'll tell you a little of the
history of this landscape. Please take the time to make sure that
you are familiar with these two exception safety guarantees. Later,
when we have gained some altitude we will find that there is
another peak in the mountain range: the no-throw exception safety
guarantee - as the name suggests this implies that <tt class=
"function">f()</tt> will never propagate an exception.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e184" id="d0e184"></a>A History of
This Territory</h2>
</div>
<p>The C++ people first came to visit the land of exceptions around
1990 when Margaret Ellis and Bjarne Stroustrup published the
<i class="citetitle">Annotated Reference Manual</i> [<a href=
"#Ellis-">Ellis-</a>]. Under the heading &quot;experimental features&quot;
this described the basic mechanisms of exceptions in the language.
In this early bestiary there is an early description of one of the
friendly beasts we shall be meeting later on: it goes by the
strange name of RESOURCE ACQUISITION IS INITIALISATION.</p>
<p>By the time the ISO C++ Standards committee circulated Committee
Draft 1 in early 1995 C++ people were truly living in exception
land. They hadn't really mapped the territory or produced an
accurate bestiary but they were committed to staying and it was
expected that these would soon be available.</p>
<p>However, by late 1996 when Committee Draft 2 was circulated the
difficulties of this undertaking had become apparent. Around this
time there came a number of reports from individual explorers. For
example: Dave Abrahams identified the mountains we are using as
landmarks in his paper <i class="citetitle">Exception Safety</i> in
STLPort [<a href="#Abrahams">Abrahams</a>] although the basic
exception safety guarantee was originally dubbed the &quot;weak
exception safety guarantee&quot;.</p>
<p>Some other studies of the region were produced by H Muller
[<a href="#Muller">Muller</a>], Herb Sutter [<a href=
"#Sutter">Sutter</a>] and [<a href="#Sutter1">Sutter1</a>]. A
little later came a sighting of another of the friendly beast that
we will meet soon called ACQUISITION BEFORE RELEASE. This beast was
first known by a subspecies named it COPY BEFORE RELEASE and was
identified by Kevlin Henney [<a href="#Henny">Henny</a>] it is
distinguished by the resources allocated being copies of dynamic
objects.</p>
<p>By the time the ISO C++ Language Standard was published in 1998
the main tracks through the territory had been charted. In
particular there are clauses in the standard guaranteeing the
behaviour of the standard library functions in the presence of
exceptions. Also, in a number of key places within the standard,
special mention is made of another friendly beast - SWAP in its
incarnation as the <tt class="function">std::swap()</tt> template
function. We will be examining SWAP after our detour through the
tar pit.</p>
<p>Since the publication of the ISO standard more modern charts
have been produced: the author in an early version of this article
[<a href="#Griffiths">Griffiths</a>]. A similar route is followed
by Bjarne Stroustrup [<a href="#Stroustrup">Stroustrup</a>]. Herb
Sutter [<a href="#Sutter2">Sutter2</a>] takes a different route,
but the same landmarks are clearly seen.</p>
<p>OK, that's enough rest, we are going to take the obvious path
and head directly towards the strong exception safety
guarantee.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e237" id="d0e237"></a>The Tar
Pit</h2>
</div>
<p>It is time to consider an example function, and for this part of
the journey I have chosen the assignment operator for the following
class:</p>
<pre class="programlisting">
class PartOne   { /* omitted */ };
class PartTwo   { /* omitted */ };
class Whole
{
public:
    // ...Lots omitted...
    Whole&amp; operator=(const Whole&amp; rhs);
private:
    PartOne*    p1;
    PartTwo*    p2;
};
</pre>
<p>Those of you that have lived in the old country will know the
classical form for the assignment operator. It looks something like
the following:</p>
<pre class="programlisting">
Whole&amp; Whole::operator=(const Whole&amp; rhs)
{
  if (&amp;rhs != this)
  {
    delete p1;
    delete p2;
    p1 = new PartOne(*rhs.p1);
    p2 = new PartTwo(*rhs.p2);
  }
  return *this;
}
</pre>
<p>If you've not seen this before, don't worry because in the new
land it is not safe. Either of the new expressions could reasonably
throw (since at the very least they attempt to allocate memory) and
this would leave the p1 and p2 pointers dangling. In theory the
&quot;delete&quot; expressions could also throw - but in this article we will
assume that destructors never propagate exceptions. (See:
&quot;destructors that throw exceptions&quot;.)</p>
<p>The obvious solution to the problems caused by an exception
being propagated is to catch the exception and do some clean up
before throwing it again. After doing the obvious we have:</p>
<pre class="programlisting">
Whole&amp; Whole::operator=(const Whole&amp; rhs)
{
  if (&amp;rhs != this)
  {
    PartOne* t1 = new PartOne(*rhs.p1);
    try 
    {
      PartTwo* t2 = new PartTwo(*rhs.p2);
      delete p1;
      delete p2;
      p1 = t1;
      p2 = t2;
    }
    catch (...)
    {
      delete t1;
      throw;
    }
  }
  return *this;
}
</pre>
<p>Let's examine why this works:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>An exception in the first new expression isn't a problem - we
haven't yet allocated any resources or modified anything.</p>
</li>
<li>
<p>If an exception is propagated from the second new expression, we
need to release <tt class="varname">t1</tt>. So we catch it, delete
t1 and throw the exception again to let it propagate.</p>
</li>
<li>
<p>We are assuming that destructors don't throw, so we pass over
the two deletes without incident. Similarly the two assignments are
of base types (pointers) and cannot throw an exception.</p>
</li>
<li>
<p>The state of the <tt class="classname">Whole</tt> isn't altered
until we've done all the things that might throw an exception.</p>
</li>
</ol>
</div>
<p>If you peer carefully through the undergrowth you can see the
first of the friendly beasts. This one is called ACQUISITION BEFORE
RELEASE. It is recognised because the code is organised so that new
resources (the new <tt class="classname">PartOne</tt> and
<tt class="classname">PartTwo</tt>) are successfully acquired
before the old ones are released.</p>
<p>We've achieved the strong exception safety guarantee on our
first attempt! But there is some black sticky stuff on our
boots.</p>
<div class="sidebar">
<p class="title c3">Standard Algorithms and User Defined Template
Classes</p>
<p>The <tt class="function">std::swap()</tt> template functions are
one example of an algorithm implemented by the standard library. It
is also an example of one where there is a good reason for C++
users to endeavour to provide an implementation specific to the
needs of the classes and class templates that they develop. This
need is particularly significant to developers of extension
libraries - who would like to ensure that what they develop will
both work well with the library and with other extension
libraries.</p>
<p>So consider the plight of a developer who is writing a template
class <tt class="classname">Foo&lt;&gt;</tt> that takes a template
parameter <i class="parameter"><tt>T</tt></i> and wishes to SWAP
two instances of <i class="parameter"><tt>T</tt></i>. Now Foo is
being instantiated with a fundamental type, or with an instance of
any swappable type from the standard library the correct function
can be resolved by writing:</p>
<pre class="programlisting">
using std::swap;
swap(t1, t2);
</pre>
<p>However, the primary template <tt class=
"function">std::swap()</tt> that will be instantiated for other
types is guaranteed to use copy construction and assignment unless
an explicit specialisation has been provided (and this is
impractical if <i class="parameter"><tt>T</tt></i> is a
specialisation of a template class). As we have seen, copy
construction and assignment probably won't meet the requirements of
SWAP. Now this won't always matter, because a language mechanism
&quot;Argument-dependent name lookup&quot; might introduce into overload
resolution a function called <tt class="function">swap()</tt> from
the namespace in which <i class="parameter"><tt>T</tt></i> is
declared, if this is the best match for arguments of type <i class=
"parameter"><tt>T</tt></i> then it is the one that gets called and
the templates in <tt class="literal">std</tt> are ignored.</p>
<p>Now there are three problems with this:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Depending on the context of the above code Koenig Lookup
produces different results. (A library developer might reasonably
be expected to know the implications of a class member named &quot;swap&quot;
and how to deal with them - but many don't.) Most C++ users will
simply get it wrong - without any obvious errors when only the
<tt class="function">std::swap()</tt> templates are considered.</p>
</li>
<li>
<p>The standard places no requirements on functions called &quot;swap&quot;
in any namespace other than <tt class="literal">std</tt> - so there
is no guarantee that <tt class="function">bar::swap()</tt> will do
the right thing.</p>
</li>
<li>
<p>In a recent resolution of an issue the standards committee has
indicated that where one standard function/template function is
required to be used by another then the use should be fully
qualified (i.e. <tt class="literal">std::swap(t1, t2);</tt>) to
prevent the application of Koenig Lookup. If you (or I) provide
<tt class="function">yournamespace::swap()</tt> the standard
algorithms won't use it.</p>
</li>
</ol>
</div>
<p>Since the standards committee is still considering what to do
about this I can't give you a watertight recommendation. I am
hoping that in the short term a &quot;technical corrigenda&quot; will permit
users to introduce new overloads of such template functions in std.
So far as I know this technique works on all current
implementations - if you know of one where it doesn't please let me
know. In the longer term I am hoping that the core language will be
extended to permit the partial specialisation of template functions
(and also that the library changes to use partial specialisation in
place of overloading).</p>
<p>For those that follow such things this is library issue 226
(<a href=
"http://anubis.dkuug.dk/JTC1/SC22/WG21/docs/lwg-active.html"
target="_top">http://anubis.dkuug.dk/JTC1/SC22/WG21/docs/lwg-active.html</a>).</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e360" id="d0e360"></a>Tar!</h2>
</div>
<p>There are problems lying just beneath the surface of this
solution. I chose an example that would enable us to pass over the
tar pit without sinking too deep. Despite this, we've incurred
costs: the line count has doubled and it takes a lot more effort to
understand the code well enough to decide that it works.</p>
<p>If you want to, you may take some time out to convince yourself
of the existence of the tar pit - I'll wait. Try the analogous
example with three pointers to parts or replacing the pointers with
two parts whose assignment operators may throw exceptions. With
real life examples things get very messy very quickly.</p>
<p>Many people have reached this point and got discouraged. I agree
with them: routinely writing code this way is not reasonable. Too
much effort is expended on exception safety housekeeping chores
like releasing resources. If you hear that &quot;writing exception safe
code is hard&quot; or that &quot;all those <tt class=
"literal">try</tt>...<tt class="literal">catch</tt> blocks take up
too much space&quot; you are listening to someone that has discovered
the tar pit.</p>
<p>I'm now going to show you how exception handling allows you to
use less code (not more), and I'm not going to use a single
<tt class="literal">try</tt>...<tt class="literal">catch</tt> block
for the rest of the article! (In a real program the exception must
be caught somewhere - like function <tt class="function">a()</tt>
in the discussion above, but most functions simply need to let the
exceptions pass through safely.)</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e386" id="d0e386"></a>The Royal
Road</h2>
</div>
<p>There are three &quot;golden rules&quot;:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Destructors may not propagate exceptions,</p>
</li>
<li>
<p>The states of two instances of a class may be swapped without an
exception being thrown,</p>
</li>
<li>
<p>An object may own at most one resource.</p>
</li>
</ol>
</div>
<p>We've already met the first rule.</p>
<p>The second rule isn't obvious, but is the basis on which SWAP
operates and is key to exception safety. The idea of SWAP is that
for two instances of a class that owns resources exchanging the
states is feasible without the need to allocate additional
resources. Since nothing needs to be allocated, failure needn't be
an option and consequently neither must throwing an exception. (It
is worth mentioning that the no-throw guarantee is not feasible for
assignment, which may have to allocate resources.)</p>
<p>If you look at the <i class="citetitle">ISO C++ Language
Standard</i>, you'll find that <tt class=
"function">std::swap()</tt> provides the no-throw guarantee for
fundamental types and for relevant types in the standard library.
This is achieved by overloading <tt class=
"function">std::swap()</tt> - e.g. there is a template
corresponding to each of the STL containers. This looks like a good
way to approach SWAP but introducing additional overloads of
<tt class="function">std::swap()</tt> is not permitted by the
language standard. The standard does permit to explicit
specialisation of an existing <tt class="function">std::swap()</tt>
template function on user defined classes and this is what I would
recommend doing where applicable (there is an example below). The
standards committee is currently considering a defect report that
addresses the problem caused by these rules for the authors of user
defined template classes. (See: Standard Algorithms and User
Defined Template Classes.)</p>
<p>The third rule addresses the cause of all the messy exception
handling code we saw in the last section. It was because creating a
new second part might fail that we wrote code to handle it and
doubled the number of lines in the assignment operator.</p>
<p>We'll now revisit the last example and make use of the above
rules. In order to conform to the rule regarding ownership of
multiple objects we'll delegate the responsibility of resource
ownership to a couple of helper classes. I'm using the <tt class=
"classname">std::auto_ptr&lt;&gt;</tt> template to generate the
helper classes here because it is standard, not because it is the
ideal choice. (See: &quot;The Trouble With <tt class=
"classname">std::auto_ptr&lt;&gt;</tt>&quot; for reasons to avoid using
<tt class="classname">auto_ptr&lt;&gt;</tt> in this context.)</p>
<pre class="programlisting">
class Whole {
public:
  // ...Lots omitted...
  Whole&amp; operator=(const Whole&amp; rhs);
private:
  std::auto_ptr&lt;PartOne&gt;    p1;
  std::auto_ptr&lt;PartTwo&gt;    p2;
};
Whole&amp; Whole::operator=(const Whole&amp; rhs)
{
  std::auto_ptr&lt;PartOne&gt; t1(
     new PartOne(*rhs.p1));
  std::auto_ptr&lt;PartTwo&gt; t2(
     new PartTwo(*rhs.p2));
  std::swap(p1, t1);
  std::swap(p2, t2);
  return *this;
}
</pre>
<p>Not only is this shorter than the original exception-unsafe
example, it meets the strong exception safety guarantee.</p>
<p>Look at why it works:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>There are no leaks: whether the function exits normally, or via
an exception, t1 and t2 will delete the parts they currently
own.</p>
</li>
<li>
<p>The swap expressions cannot throw (second rule).</p>
</li>
<li>
<p>The state of the <tt class="classname">Whole</tt> isn't altered
until we've done all the things that might throw an exception.</p>
</li>
</ol>
</div>
<p>Oh, by the way, I've not forgotten about self-assignment. Think
about it - you will see the code works without a test for
self-assignment. Such a test may be a bad idea: assuming that
self-assignment is very rare in real code and that the branch could
have a significant cost. Francis Glassborow suggested a similar
style of assignment operator as a speed optimisation [<a href=
"#Glassborow">Glassborow</a>]. Following on from this, Kevlin
Henney explored its exception safety aspects in [<a href=
"#Henney1">Henney1</a>], [<a href="#Henney2">Henney2</a>] and
[<a href="#Henny">Henny</a>].</p>
<p>We are on much firmer ground than before: it isn't hard to see
why the code works and generalising it is simple. You should be
able to see how to manage a <tt class="classname">Whole</tt> with
three <tt class="classname">auto_ptr</tt>s to Parts without
breaking stride.</p>
<p>You can also see another of the friendly beasts for the first
time. Putting the allocation of a resource (here a new expression)
into the initialiser of an instance of a class (eg <tt class=
"literal">auto_ptr&lt;PartOne&gt;</tt>) that will delete it on
destruction is RESOURCE ACQUISITION IS INITIALISATION. And, of
course, we can once again see ACQUISITION BEFORE RELEASE.</p>
<p>(Yes, in this case we could use assignment instead of SWAP to
make the updates. However with a more complex type SWAP is
necessary, as we shall see later. I use SWAP in this example for
consistency.)</p>
<div class="sidebar">
<p class="title c3">The Trouble With std::auto_ptr&lt;&gt;</p>
<p>By historical accident, the standard library provides a single
smart pointer template known as <tt class=
"classname">auto_ptr&lt;&gt;</tt>. <tt class=
"classname">auto_ptr&lt;&gt;</tt> has what I will politely describe
as &quot;interesting&quot; copy semantics. Specifically, if one <tt class=
"classname">auto_ptr&lt;&gt;</tt> is assigned (or copy constructed)
from another then they are both changed - the <tt class=
"classname">auto_ptr&lt;&gt;</tt> that originally owned the object
loses ownership and becomes 0. This is a trap for the unwary
traveller! There are situations that call for this behaviour, but
on most occasions that require a smart pointer the copy semantics
cause a problem.</p>
<p>When we replace <tt class="literal">PartXXX*</tt> with
<tt class="literal">auto_ptr&lt;PartXXX&gt;</tt> in the <tt class=
"classname">Whole</tt> class we still need to write the copy
constructor and assignment operator carefully to avoid any
<tt class="literal">PartXXX</tt> being passed from one <tt class=
"classname">Whole</tt> to another (with the consequence that one
<tt class="classname">Whole</tt> loses its <tt class=
"literal">PartXXX</tt>).</p>
<p>Another effect of the odd copy behaviour is that <tt class=
"classname">auto_ptr</tt> does not meet the constraints stated in
the standard for the <tt class="function">std::swap</tt> template.
So, technically the code in the <tt class="function">main</tt> body
isn't guaranteed to work. However, having discussed this issue in
the &quot;library&quot; group of the standards committee it is clear that
<tt class="function">std::swap</tt> is intended to work with
<tt class="classname">auto_ptr&lt;&gt;</tt>, and that no
&quot;reasonable&quot; implementation would fail.</p>
<p>We encounter a further problem if we attempt to hide the
implementation of <tt class="literal">PartXXX</tt> from the client
code by using a forward declaration: we would also need to write
the destructor. If we don't, the one the compiler generates for us
will not correctly destroy the <tt class="literal">PartXXX</tt>.
This is because the client code causes the generation of the
<tt class="classname">Whole</tt> destructor and consequently
instantiates the <tt class="classname">auto_ptr&lt;&gt;</tt>
destructor without having seen the class definition for <tt class=
"literal">PartXXX</tt>. Technically, this is forbidden by the
standard. But, as no diagnostic is required, the effect of this is
typically to instantiate the <tt class="classname">auto_ptr</tt>
destructor. This deletes an incomplete type - unless <tt class=
"literal">PartXXX</tt> has a trivial destructor this gives
&quot;undefined behaviour&quot;.</p>
<p>Although the standard library doesn't support our needs for a
smart pointer very well it is possible to write ones which do.
There are a couple of examples in the <span class=
"application">arglib</span> library on my website.</p>
<p>(Both <tt class="classname">arg::body_part_ptr&lt;&gt;</tt> and
<tt class="classname">arg::grin_ptr&lt;&gt;</tt> are more suitable
than <tt class="classname">std::auto_ptr&lt;&gt;</tt>.) An
excellent C++ library (that contains smart pointers) is boost
[<a href="#boost">boost</a>].</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e582" id="d0e582"></a>The
Assignment Operator - a Special Case</h2>
</div>
<p>Before I go on to deal with having members that may throw when
updated, I've a confession I need to make. It is possible, and
usual, to write the assignment operator more simply than the way
I've just demonstrated. The above method is more general than what
follows and can be applied when only some aspects of the state are
being modified. The following applies only to assignment:</p>
<pre class="programlisting">
Whole&amp; Whole::operator=(const Whole&amp; rhs)
{
  Whole(rhs).swap(*this);
  Return *this;
}
</pre>
<p>Remember the second rule: Whole is a good citizen and provides
for SWAP (by supplying the <tt class="function">swap()</tt> member
function). I also make use of the copy constructor - but it would
be a perverse class design that supported assignment but not copy
construction. I'm not sure whether the zoologists have determined
the relationship between SWAP and copying here, but the traveller
won't go far wrong in considering COPY AND SWAP as species in it
own right.</p>
<p>For completeness, I'll show the methods used above:</p>
<pre class="programlisting">
void Whole::swap(Whole&amp; that)
{
  std::swap(p1, that.p1);
  std::swap(p2, that.p2);
}
Whole::Whole(const Whole&amp; rhs)
:   p1(new PartOne(*rhs.p1)),
    p2(new PartTwo(*rhs.p2))
{
}
</pre>
<div class="sidebar">
<p class="title c3">The Cost of Exception Handling</p>
<p>Compiler support for exception handling does make the generated
code bigger (figures vary around 10-15%), but only for the same
code. However, code isn't written the same way without exceptions -
for example, since constructors cannot return an error code, idioms
such as &quot;two phase construction&quot; are required. I have here a
comparable piece of code to the final example that has been handed
down the generations from a time before the introduction of
exception handling to C++. (Actually I've made it up - but I was
around back then and remember working with code like this, so it is
an authentic fake.)</p>
<pre class="programlisting">
int ExtendedWhole::setParts(
  const PartOne&amp; p1,
  const PartTwo&amp; p2,
  const PartThree&amp; p3)
{
  Whole tw;
  int rcode = tw.init(*this);
  if (!rcode) rcode = tw.setP1(p1);
  if (!rcode) rcode = tw.setP2(p2);
  if (!rcode)
  {
    PartThree t3;
    Rcode = t3.copy(p3);
    If (!rcode)
    {
      Whole::swap(tw);
      body.swap(t3);
   }
  }
  return rcode;
}
</pre>
<p>To modern eyes the need to repeat this testing and branch on
return codes looks very like the tar-pit we encountered earlier -
it is verbose, hard to validate code. I'm not aware of any trials
where comparable code was developed using both techniques, but my
expectation is that the saving in hand-written code from using
exceptions significantly outweighs the extra cost in
compiler-generated exception handling mechanisms.</p>
<p>Please don't take this as a rejection of return codes, they are
one of the primary error reporting mechanisms in C++. But if an
operation will only fail in exceptional circumstances (usually
running out of a resource) or cannot reasonably be expected to be
dealt with by the code at the call site then exceptions can greatly
simplify the task.</p>
</div>
<p>One further point about making Whole a good citizen is that we
need to specialise <tt class="function">std::swap()</tt> to work
through the swap() member function. By default <tt class=
"function">std::swap()</tt> will use assignment - and not deliver
the no-throw guarantee we need for SWAP. The standard allows us to
specialise existing names in the <tt class="literal">std</tt>
namespace on our own types, and it is good practice to do so in the
header that defines the type.</p>
<pre class="programlisting">
Namespace std
{
  template&lt;&gt;
  inline void swap(exe::Whole&amp; lhs,
                   exe::Whole&amp; rhs)
  {
    lhs.swap(rhs);
  }
}
</pre>
<p>This avoids any unpleasant surprises for client code that
attempts to <tt class="function">swap()</tt> two <tt class=
"classname">Whole</tt>s.</p>
<p>Although we've focused on attaining the higher peak of strong
exception safety guarantee, we've actually covered all the
essential techniques for achieving either strong or basic exception
safety. The remainder of the article shows the same techniques
being employed in a more complex example and gives some indication
of the reasons you might choose to approach the lesser altitudes of
basic exception safety.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e632" id="d0e632"></a>In Bad
Weather</h2>
</div>
<p>We can't always rely on bright sunshine, or on member variables
that are as easy to manipulate as pointers. Sometimes we have to
deal with rain and snow, or base classes and member variables with
internal state.</p>
<p>To introduce a more complicated example, I'm going to elaborate
the <tt class="classname">Whole</tt> class we've just developed by
adding methods that update <tt class="varname">p1</tt> and
<tt class="varname">p2</tt>. Then I'll derive an <tt class=
"classname">ExtendedWhole</tt> class from it that also contains an
instance of another class: <tt class="classname">PartThree</tt>.
We'll be assuming that operations on <tt class=
"classname">PartThree</tt> are exception safe, but, for the
purposes of discussion, I'll leave it open whether <tt class=
"classname">PartThree</tt> offers the basic or the strong exception
safety guarantee.</p>
<pre class="programlisting">
Whole&amp; Whole::setP1(const PartOne&amp; value)
{
  p1.reset(new PartOne(value));
  return *this;
}
Whole&amp; Whole::setP2(const PartTwo&amp; value)
{
  p2.reset(new PartTwo(value));
  return *this;
}
class ExtendedWhole : private Whole
{
public:
  // Omitted constructors &amp; assignment
  void swap(const ExtendedWhole&amp; rhs);
  void setParts(
    const PartOne&amp; p1,
    const PartTwo&amp; p2,
    const PartThree&amp; p3);
private:
  int       count;
  PartThree body;
};
</pre>
<p>The examples we've looked at so far are a sufficient guide to
writing the constructors and assignment operators. We are going to
focus on two methods: the <tt class="function">swap()</tt> member
function and a <tt class="function">setParts()</tt> method that
updates the parts.</p>
<p>Writing <tt class="function">swap()</tt> looks pretty easy - we
just swap the base class, and each of the members. Since each of
these operations is &quot;no-throw&quot; the combination of them is also
&quot;no-throw&quot;.</p>
<pre class="programlisting">
void ExtendedWhole::swap(ExtendedWhole&amp; rhs)
{
  Whole::swap(rhs);
  std::swap(count, rhs.count);
  std::swap(body,  rhs.body);
}
</pre>
<p>Writing <tt class="function">setParts()</tt> looks equally easy:
<tt class="classname">Whole</tt> provides methods for setting
<tt class="varname">p1</tt> and <tt class="varname">p2</tt>, and we
have access to body to set that. Each of these operations is
exception safe, indeed the only one that need not make the strong
exception safety guarantee is the assignment to body. Think about
it for a moment: is this version of <tt class=
"function">setParts()</tt> exception safe? And does it matter if
the assignment to body offers the basic or strong guarantee?</p>
<pre class="programlisting">
void ExtendedWhole::setParts(
  const PartOne&amp; p1,
  const PartTwo&amp; p2,
  const PartThree&amp; p3)
{
  setP1(p1);
  setP2(p2);
  body = p3;
}
</pre>
<p>Let's go through it together, none of the operations leak
resources, and <tt class="function">setParts()</tt> doesn't
allocate any so we don't have any leaks. If an exception propagates
from any of the operations, then they leave the corresponding
sub-object in a useable state, and presumably that leaves
<tt class="classname">ExtendedWhole</tt> useable (it is possible,
but in this context implausible, to construct examples where this
isn't true). However, if an exception propagates from <tt class=
"function">setP2()</tt> or from the assignment then the system
state has been changed. And this is so regardless of which
guarantee <tt class="classname">PartThree</tt> makes.</p>
<p>The simple way to support the strong exception safety guarantee
it to ensure that nothing is updated until we've executed all the
steps that might throw an exception. This means taking copies of
sub-objects and making the changes on the copies, prior to swapping
the state between the copies and the original sub-objects:</p>
<pre class="programlisting">
Void ExtendedWhole::setParts(
  Const PartOne&amp; p1,
  Const PartTwo&amp; p2,
  Const PartThree&amp; p3)
{
  Whole temp(*this);
  Temp.setP1(p1).setP2(p2);
  Body = p3;
  Whole::swap(temp);
}
</pre>
<p>Once again does it matter if the assignment to body offers the
basic or strong guarantee? Yes it does, if it offers the strong
guarantee then all is well with the above, if not then the
assignment needs to be replaced with COPY AND SWAP vis:</p>
<pre class="programlisting">
PartThree(p3).swap(body);
</pre>
<p>Once again we have attained the highest peak, but this may not
be healthy. On terrestrial mountains above a certain height there
is a &quot;death zone&quot; where the supply of oxygen is insufficient to
support life. Something similar happens with exception safety:
there is a cost to implementing the strong exception safety
guarantee. Although the code you write isn't much more complicated
than the 'basic' version, additional objects are created and these
allocate resources at runtime. This causes the program to make more
use of resources and to spend time allocating and releasing
them.</p>
<p>Trying to remain forever at high altitude will drain the
vitality. Fortunately, the basic exception safety guarantee is
below the death zone: when one makes a composite operation whose
parts offer this guarantee one automatically attains the basic
guarantee (as the first version of <tt class=
"function">setParts()</tt> shows this is not true of the strong
guarantee). From the basic guarantee there is an easy climb from
this level to the strong guarantee by means of COPY AND SWAP.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e725" id="d0e725"></a>Looking
Back</h2>
</div>
<p>Before we descend from the peak of strong exception safety
guarantee and return to our starting point look back over the route
we covered. In the distance you can see the well-trampled path that
led to the tar pit and just below us the few tracks leading from
the tar pit up a treacherous scree slope to where we stand. Off to
the left is the easier ridge path ascending from basic exception
safety guarantee and beyond that the road that led us past the tar
pit. Fix these landmarks in your mind and remember that the beasts
we met are not as fierce as their reputations.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e730" id="d0e730"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Ellis-" id="Ellis-"></a>
<p class="bibliomixed">[Ellis-] Ellis &amp; Stroustrup,
<span class="citetitle"><i class="citetitle">The Annotated C++
Reference Manual</i></span> ISBN 0-201-51459-1</p>
</div>
<div class="bibliomixed"><a name="Abrahams" id="Abrahams"></a>
<p class="bibliomixed">[Abrahams] Abrahams, Dave Exception Safety
in STLPort <span class="bibliomisc"><a href=
"http://www.stlport.org/doc/exception_safety.html" target=
"_top">http://www.stlport.org/doc/exception_safety.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Muller" id="Muller"></a>
<p class="bibliomixed">[Muller] Muller, H Ten rules for handling
exception handling successfully <span class="citetitle"><i class=
"citetitle">C++ Report</i></span> Jan.'96</p>
</div>
<div class="bibliomixed"><a name="Sutter" id="Sutter"></a>
<p class="bibliomixed">[Sutter] Sutter, Herb Designing
exception-safe Generic Containers <span class="citetitle"><i class=
"citetitle">C++ Report</i></span> Sept.'97</p>
</div>
<div class="bibliomixed"><a name="Sutter1" id="Sutter1"></a>
<p class="bibliomixed">[Sutter1] Sutter, Herb More exception-safe
Generic Containers <span class="citetitle"><i class="citetitle">C++
Report</i></span> Nov-Dec.'97</p>
</div>
<div class="bibliomixed"><a name="Henny" id="Henny"></a>
<p class="bibliomixed">[Henny] Henny, Kevlin Creating Stable
Assignments <span class="citetitle"><i class="citetitle">C++
Report</i></span> June'98</p>
</div>
<div class="bibliomixed"><a name="Griffiths" id="Griffiths"></a>
<p class="bibliomixed">[Griffiths] Griffiths, Alan The safe path to
C++ exceptions <span class="citetitle"><i class=
"citetitle">EXE</i></span> Dec.'99</p>
</div>
<div class="bibliomixed"><a name="Stroustrup" id="Stroustrup"></a>
<p class="bibliomixed">[Stroustrup] Stroustrup, Bjarne <span class=
"citetitle"><i class="citetitle">The C++ Programming
Language</i></span> (3rd Edition) appendix E &quot;Standard Library
Exception Safety&quot; (this appendix dies not appear in early
printings, but is available on the web at <span class=
"bibliomisc"><a href="http://www.research.att.com/~bs/3rd_safe.pdf"
target=
"_top">http://www.research.att.com/~bs/3rd_safe.pdf</a></span>)</p>
</div>
<div class="bibliomixed"><a name="Sutter2" id="Sutter2"></a>
<p class="bibliomixed">[Sutter2] Sutter, Herb <span class=
"citetitle"><i class="citetitle">Exceptional C++</i></span> ISBN
0-201-61562-2</p>
</div>
<div class="bibliomixed"><a name="Glassborow" id="Glassborow"></a>
<p class="bibliomixed">[Glassborow] Glassborow, Francis, &quot;The
Problem of Self-Assignment&quot; in <span class="citetitle"><i class=
"citetitle">Overload 19</i></span> ISSN 1354-3172</p>
</div>
<div class="bibliomixed"><a name="Henney1" id="Henney1"></a>
<p class="bibliomixed">[Henney1] Henney, Kevlin &quot;Self Assignment?
No Problem!&quot; in <span class="citetitle"><i class=
"citetitle">Overload 20</i></span> ISSN 1354-3172</p>
</div>
<div class="bibliomixed"><a name="Henney2" id="Henney2"></a>
<p class="bibliomixed">[Henney2] Henney, Kevlin &quot;Self Assignment?
No Problem!&quot; in <span class="citetitle"><i class=
"citetitle">Overload 21</i></span> ISSN 1354-3172</p>
</div>
<div class="bibliomixed"><a name="boost" id="boost"></a>
<p class="bibliomixed">[boost] <span class="bibliomisc"><a href=
"http://www.boost.org/" target=
"_top">http://www.boost.org/</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>
