    <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  :: Here be Dragons</title>
        <link>https://members.accu.org/index.php/journals/469</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>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #40 - Dec 2000 + Programming Topics</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/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c164/">40</a>
                    (5)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c164-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c164+65/">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;Here be Dragons</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 December 2000 16:46:04 +00:00 or Tue, 26 December 2000 16:46:04 +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 am Alan
Griffiths and I am 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 do not skip it in the hope of
getting to the good stuff - if you do not take the time to get your
bearings now you will end up in the wastelands.</p>
<p>Once I have established the bearings I will show you a
well-trodden path that leads straight towards the highest peak and
straight through a tar pit. From experience, I have concluded that
everyone has to go down this way once. So I will 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 will 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 do not show it yet, but
I will show you the signs to look out for. I will also show you
that the beasts are friendly and how to enlist their aid.</p>
<p>If you look into the distance you will 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 will 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 is not 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 am 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
<tt class="function">b()</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 am not going to spend any time on how to write functions
<tt class="function">a()</tt> or <tt class="function">x()</tt>. I
am 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 will not be
handled until we reach <tt class="function">a()</tt>. Since
<tt class="function">f()</tt> does not run to completion we might
reasonably expect that:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p><tt class="function">f()</tt> does not 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>
<p>In summary: If <tt class="function">f()</tt> updates the system
state, then the state must remain valid. Note that is not 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 am 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 will 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>
</li>
<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 is not 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>
<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 will rest here a while, and I will 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 <span class=
"emphasis"><em>no-throw exception safety guarantee</em></span> - 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="d0e154" id="d0e154"></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
&quot;Annotated Reference Manual&quot; [<a href="#ARM">ARM</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 As
Initialisation.</p>
<p>By the time the ISO C++ Standards committee circulated
&quot;Committee Draft 1&quot; in early 1995 C++ people were truly living in
exception land. They had not 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>
<div class="sidebar">
<p class="title c2">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 (i.e. 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.) If
you look at the standard library containers, you will find that
they place certain requirements on the types that are supplied as
template parameters. One of these is that the destructor does not
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 should not throw, or
releasing resources - and if that fails an exception will not
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>However, by late 1996 when &quot;Committee Draft 2&quot; 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 &quot;Exception Safety in STLPort&quot; [<a href=
"#ESS">ESS</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="#TEN">TEN</a>], Herb Sutter [<a href="#DGC">DGC</a>] and
[<a href="#MGC">MGC</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=
"#CSA">CSA</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 - <span class=
"emphasis"><em>Swap</em></span> in its incarnation as the
<tt class="function">std::swap()</tt> template function. We will be
examining <span class="emphasis"><em>Swap</em></span> 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="#TSP">TSP</a>]. A similar route is followed by Bjarne
Stroustrup [<a href="#SLE">SLE</a>]. Herb Sutter [<a href=
"#EC">EC</a>] takes a different route, but the same landmarks are
clearly seen.</p>
<p>OK, that is 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 have not seen this before, do not worry because in the
new land <span class="underline">it is not safe</span>. Either of
the <tt class="literal">new</tt> expressions could reasonably throw
(since at the very least they attempt to allocate memory) and this
would leave the <tt class="varname">p1</tt> and <tt class=
"varname">p2</tt> pointers dangling. In theory the &quot;<tt class=
"literal">delete</tt>&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>
<div class="sidebar">
<p class="title c2">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 <tt class="type">T</tt> and wishes to <span class=
"emphasis"><em>Swap</em></span> two instances of <tt class=
"type">T</tt>. Now <tt class="classname">Foo</tt> 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 <tt class="type">T</tt> is a specialisation of a
template class). As we have seen, copy construction and assignment
probably will not meet the requirements of <span class=
"emphasis"><em>Swap</em></span>. Now this will not always matter,
because a language mechanism &quot;Argument-dependent name lookup&quot;
(commonly know as &quot;Koenig Lookup&quot;) might introduce into overload
resolution a function called <tt class="function">swap()</tt> from
the namespace in which <tt class="type">T</tt> is declared, if this
is the best match for arguments of type <tt class="type">T</tt>
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;<tt class="function">swap</tt>&quot; and how to deal with them - but
many do not.) 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;<tt class="function">swap</tt>&quot; in any <tt class=
"literal">namespace</tt> 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 will not use it.</p>
</li>
</ol>
</div>
<p>Since the standards committee is still considering what to do
about this I cannot 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
<tt class="literal">std</tt>. So far as I know this technique works
on all current implementations - if you know of one where it does
not 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>
<p>Let us examine why this works&hellip;</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>An exception in the first <tt class="literal">new</tt>
expression is not a problem - we have not yet allocated any
resources or modified anything.</p>
</li>
<li>
<p>If an exception is propagated from the second <tt class=
"literal">new</tt> expression, we need to release <tt class=
"varname">t1</tt>. So we catch it, <tt class="literal">delete</tt>
<tt class="varname">t1</tt> and <tt class="literal">throw</tt> the
exception again to let it propagate.</p>
</li>
<li>
<p>We are assuming that destructors do not throw, so we pass over
the two <tt class="literal">delete</tt>s 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> is not altered
until we have 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 <i class=
"firstterm">Acquisition Before Release</i>. 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 have achieved the strong exception safety guarantee on our
first attempt. But there is some black sticky stuff on our
boots.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e417" id="d0e417"></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 have 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 will 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">...</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 am now going to show you how exception handling allows you to
use less code (not more), and I am not going to use a single
<tt class="literal">try</tt><tt class="literal">...</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
<span class="emphasis"><em>safely</em></span>.)</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e448" id="d0e448"></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 have already met the first rule.</p>
<p>The second rule is not obvious, but is the basis on which
<span class="emphasis"><em>Swap</em></span> operates and is key to
exception safety. The idea of <span class=
"emphasis"><em>Swap</em></span> 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 need not 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 ISO C++ Language Standard, you will 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 <span class="emphasis"><em>Swap</em></span> 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 will 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 will delegate the responsibility of resource
ownership to a couple of helper classes. I am 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>
<div class="sidebar">
<p class="title c2">The Trouble With <tt class=
"classname">std::auto_ptr&lt;&gt;</tt></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="classname">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 an
<tt class="classname">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=
"classname">PartXXX</tt>).</p>
<p>Worse than this, if we attempt to hide the implementation of
<tt class="classname">PartXXX</tt> from the client code using a
forward declaration we also need to write the destructor. If we do
not, the one the compiler generates for us will not correctly
destroy the <tt class="classname">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=
"classname">PartXXX</tt>. The effect of this is that the destructor
of <tt class="classname">PartXXX</tt> is never called. (A good
compiler may give a cryptic warning about deleting an incomplete
type, but the language standard requires that the code compiles -
although the results are unlikely to be what the programmer
intended.)</p>
<p>Although the standard library does not support our needs very
well it is possible to write smart pointers that do. There are some
examples in the &quot;<tt class="literal">arglib</tt>&quot; library on my
website. (Both <tt class=
"classname">arg::body_part_ptr&lt;&gt;</tt> and &quot;<tt class=
"classname">arg::grin_ptr&lt;&gt;</tt>&quot; are more suitable than
<tt class="classname">std::auto_ptr&lt;&gt;</tt>.)</p>
</div>
<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, <tt class="varname">t1</tt> and <tt class=
"varname">t2</tt> 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> is not altered
until we have done all the things that might throw an
exception.</p>
</li>
</ol>
</div>
<p>Oh, by the way, I have 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=
"#PSA">PSA</a>]. Following on from this, Kevlin Henney explored its
exception safety aspects in [<a href="#SAN20">SAN20</a>], [<a href=
"#SAN21">SAN21</a>] and [<a href="#CSA">CSA</a>].</p>
<p>We are on much firmer ground than before: it is not 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 <tt class=
"classname">Part</tt>s 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 <tt class=
"literal">new</tt> expression) into the initialiser of an instance
of a class (e.g. <tt class="literal">auto_ptr&lt;PartOne&gt;</tt>)
that will delete it on destruction is <span class=
"emphasis"><em>Resource Acquisition Is Initialisation</em></span>.
And, of course, we can once again see <span class=
"emphasis"><em>Acquisition Before Release</em></span>.</p>
<p>(Yes, in this case we could use assignment instead of
<span class="emphasis"><em>Swap</em></span> to make the updates.
However with a more complex type <span class=
"emphasis"><em>Swap</em></span> is necessary, as we shall see
later. I use <span class="emphasis"><em>Swap</em></span> in this
example for consistency.)</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e654" id="d0e654"></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 have a confession I need to make. It is possible, and
usual, to write the assignment operator more simply than the way I
have 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>
<div class="sidebar">
<p class="title c2">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
<span class="underline">same code</span>. However, code is not
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 have 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 &amp; branch on
return codes looks very like the tar-pit we encountered earlier -
it is verbose, hard to validate code. I am 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 do not 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>
<pre class="programlisting">
Whole&amp; Whole::operator=(const Whole&amp; rhs){
  Whole(rhs).swap(*this);
  return *this;
}
</pre>
<p>Remember the second rule: <tt class="classname">Whole</tt> is a
good citizen and provides for <span class=
"emphasis"><em>Swap</em></span> (by supplying the <tt class=
"methodname">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 am not sure
whether the zoologists have determined the relationship between
<span class="emphasis"><em>Swap</em></span> and copying here, but
the traveller will not go far wrong in considering <span class=
"emphasis"><em>Copy</em></span> And <span class=
"emphasis"><em>Swap</em></span> as species in it own right.</p>
<p>For completeness, I will 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>
<p>One further point about making <tt class="classname">Whole</tt>
a good citizen is that we need to specialise <tt class=
"function">std::swap()</tt> to work through the <tt class=
"methodname">swap()</tt> member function. By default <tt class=
"function">std::swap()</tt> will use assignment - and not deliver
the no-throw guarantee we need for <span class=
"emphasis"><em>Swap</em></span>. The standard allows us to
specialise existing names in the <tt class="literal">std</tt>
<tt class="literal">namespace</tt> 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 have focused on attaining the higher peak of strong
exception safety guarantee, we have 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="d0e734" id="d0e734"></a>In bad
weather</h2>
</div>
<p>We cannot 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 am going to elaborate
the <tt class="classname">Whole</tt> class we have just developed
by adding methods that update <tt class="varname">p1</tt> and
<tt class="varname">p2</tt>. Then I will derive an <tt class=
"classname">ExtendedWhole</tt> class from it that also contains an
instance of another class: <tt class="classname">PartThree</tt>. We
will be assuming that operations on <tt class=
"classname">PartThree</tt> are exception safe, but, for the
purposes of discussion, I will 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 have 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="methodname">swap()</tt> member
function and a <tt class="methodname">setParts()</tt> method that
updates the parts.</p>
<p>Writing <tt class="methodname">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="methodname">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=
"methodname">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 us go through it together, none of the operations leak
resources, and <tt class="methodname">setParts()</tt> does not
allocate any so we do not 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 is not true). However, if an exception propagates from
<tt class="methodname">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 have 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 <span class=
"emphasis"><em>Copy</em></span> And <span class=
"emphasis"><em>Swap</em></span> 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 is not 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=
"methodname">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 <span class=
"emphasis"><em>Copy</em></span> And <span class=
"emphasis"><em>Swap</em></span>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e839" id="d0e839"></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 class="bibliography">
<div class="titlepage">
<h2><a name="d0e844" id="d0e844"></a>References</h2>
</div>
<div class="bibliomixed"><a name="ARM" id="ARM"></a>
<p class="bibliomixed">[ARM] &quot;<span class="citetitle"><i class=
"citetitle">The Annotated C++ Reference Manual</i></span>&quot;, Ellis
&amp; Stroustrup, ISBN 0-201-51459-1.</p>
</div>
<div class="bibliomixed"><a name="ESS" id="ESS"></a>
<p class="bibliomixed">[ESS] &quot;<span class="citetitle"><i class=
"citetitle">Exception Safety in STLPort</i></span>&quot;, Dave Abrahams,
<span class="bibliomisc"><a href=
"http://www.stlport.org/doc/%20exception_safety.html" target=
"_top">http://www.stlport.org/doc/
exception_safety.html</a></span></p>
</div>
<div class="bibliomixed"><a name="TEN" id="TEN"></a>
<p class="bibliomixed">[TEN] &quot;Ten rules for handling exception
handling successfully&quot;, H Muller, <span class="citetitle"><i class=
"citetitle">C++ Report</i></span> Jan '96.</p>
</div>
<div class="bibliomixed"><a name="DGC" id="DGC"></a>
<p class="bibliomixed">[DGC] &quot;Designing exception-safe Generic
Containers&quot;, Herb Sutter, <span class="citetitle"><i class=
"citetitle">C++ Report</i></span> Sept '97.</p>
</div>
<div class="bibliomixed"><a name="MGC" id="MGC"></a>
<p class="bibliomixed">[MGC] &quot;More exception-safe Generic
Containers&quot;, Herb Sutter, <span class="citetitle"><i class=
"citetitle">C++ Report</i></span> Nov-Dec '97.</p>
</div>
<div class="bibliomixed"><a name="CSA" id="CSA"></a>
<p class="bibliomixed">[CSA] &quot;Creating Stable Assignments&quot;, Kevlin
Henney, <span class="citetitle"><i class="citetitle">C++
Report</i></span> June '98.</p>
</div>
<div class="bibliomixed"><a name="TSP" id="TSP"></a>
<p class="bibliomixed">[TSP] &quot;The safe path to C++ exceptions&quot;,
Alan Griffiths, <span class="citetitle"><i class=
"citetitle">EXE</i></span> Dec.'99.</p>
</div>
<div class="bibliomixed"><a name="SLE" id="SLE"></a>
<p class="bibliomixed">[SLE] &quot;<span class="citetitle"><i class=
"citetitle">The C++ Programming Language (3rd Edition)</i></span>&quot;
appendix E &quot;Standard Library Exception Safety&quot;, Bjarne Stroustrup.
(this appendix does not appear in early printings, but available on
the web at <span class="bibliomisc"><a href=
"http://www.research.att.com/~bs/3rd_safe.pdf" target=
"_top">www.research.att.com/~bs/3rd_safe.pdf</a></span>)</p>
</div>
<div class="bibliomixed"><a name="EC" id="EC"></a>
<p class="bibliomixed">[EC] &quot;<span class="citetitle"><i class=
"citetitle">Exceptional C++</i></span>&quot;, Herb Sutter, ISBN
0-201-61562-2.</p>
</div>
<div class="bibliomixed"><a name="PSA" id="PSA"></a>
<p class="bibliomixed">[PSA] &quot;The Problem of Self-Assignment&quot;,
Francis Glassborow, <span class="citetitle"><i class=
"citetitle">Overload 19</i></span> ISSN 1354-3172.</p>
</div>
<div class="bibliomixed"><a name="SAN20" id="SAN20"></a>
<p class="bibliomixed">[SAN20] &quot;Self Assignment? No Problem!&quot;,
Kevlin Henney, <span class="citetitle"><i class=
"citetitle">Overload 20</i></span> ISSN 1354-3172.</p>
</div>
<div class="bibliomixed"><a name="SAN21" id="SAN21"></a>
<p class="bibliomixed">[SAN21] &quot;Self Assignment? No Problem!&quot;,
Kevlin Henney, <span class="citetitle"><i class=
"citetitle">Overload 21</i></span> ISSN 1354-3172</p>
</div>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
