    <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  :: A Little Detail</title>
        <link>https://members.accu.org/index.php/articles/304</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #60 - Apr 2004</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

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

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

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

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c152/">60</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+152/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;A Little Detail</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 April 2004 22:54:59 +01:00 or Fri, 02 April 2004 22:54:59 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>Some time ago I wrote a simple mixin class template. A week
later I found a little problem with it. Although I found a solution
in a second I decided to analyse it more deeply. It's worth
analysing further because it concerns some fundamental features of
C++.</p>
<p>Here is the problematic code:</p>
<pre class="programlisting">
template&lt;class T&gt;
struct Mixin : T {
  ~Mixin();
};
</pre>
<p>I guess I know your feelings. The class template looks like an
example taken from a C++ book. You might have been taught with code
like this. Your feelings about it most likely are based on
unchallenged assumptions about simple C++ language constructs.
Despite its basic nature the code has one little problem.</p>
<p>Why does this code look nice at first glance? Well, if it was an
ordinary class you could just compile it and see that everything is
fine. But the &quot;just compile it&quot; idea doesn't work in the case of
class templates. Actually, writing the code is only half the job.
The second half is instantiating the template. This will be done by
the user unless you think of all possible cases and instantiate
them in your tests.</p>
<p>This is a different way of thinking. If you deal with templates
you should imagine how different instantiations could be compiled.
You can tell me &quot;Hey, what's the problem, I can write tests and
instantiate the template there&quot;. Yes, you can. But first you have
to find the right classes for instantiations. As an example, can
you find an instantiation of <tt class=
"classname">Mixin&lt;X&gt;</tt> that breaks the code above?</p>
<p>Don't think too much, I have an answer. Here it is:</p>
<pre class="programlisting">
struct X {
  virtual ~X() throw();
};
</pre>
<p>Once the right class is found you can try to compile it. My
compiler (g++ 3.2.2) complains:</p>
<pre class="screen">
1.cpp: In instantiation of 'Mixin&lt;X&gt;':
1.cpp:12: instantiated from here
1.cpp:3: looser throw specifier for 'void Mixin&lt;T&gt;::Mixin() [with T = X]'
1.cpp:7: overriding 'virtual X::~X() throw ()'
</pre>
<p>According to our best friend, the C++ standard [<a href=
"#ISO">ISO</a>], paragraph 15.4, bullet 3:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>If a virtual function has an exception-specification, all
declarations, including the definition, of any function that
overrides that virtual function in any derived class shall only
allow exceptions that are allowed by the exception-specification of
the base class virtual function.</p>
</blockquote>
</div>
<p>None is allowed in a destructor of base class X. Therefore, none
should be allowed in a destructor of the derived class <tt class=
"classname">Mixin&lt;X&gt;</tt>:</p>
<pre class="programlisting">
template&lt;class T&gt;
struct Mixin : T {
  ~Mixin() throw();
};
</pre>
<p>Well, we found a quick solution to the problem. Does it have
some drawbacks? Can it break other instantiations? For example,
what if <span class="type">T</span>'s destructor may occasionally
throw? <tt class="classname">Mixin&lt;X&gt;</tt> has an empty
exception specification list, therefore, <tt class=
"classname">std::unexpected</tt> will be called. This function will
call <tt class="function">std::terminate</tt> and program execution
will be aborted. This is definitely not what a user wants.</p>
<p>Luckily, many C++ gurus recommend not throwing exceptions in the
destructor at all. It's enough to mention in the documentation of
<tt class="classname">Mixin</tt> that the destructor of
<span class="type">T</span> must meet the <tt class=
"literal">Nothrow</tt> requirement.</p>
<p>It seems that the problem is solved. Indeed, if you're a bug
hunter who has just ended up with code like that above you can stop
reading here. I'd rather analyze it a little bit more.</p>
<p>What is annoying me in a destructor with an empty exception
specification is the fact that a compiler may put the destructor's
code into a try-catch block. It protects your application against
&quot;exception leaks&quot;. The try-catch block can be omitted only if the
destructor's body is available and the compiler can deduce that the
destructor never throws. Otherwise, unnecessary try-catch blocks
make the code bigger and execution slower.</p>
<p>Another inconvenience of the code was suggested by Phil Bass
while reviewing this article. His concern is a design flaw rather
than implementation details. Phil suggested that, if <tt class=
"classname">Mixin</tt> is part of a general-purpose library, it
would be great if <tt class="classname">Mixin</tt> were to follow a
project-specific exception specification policy.</p>
<p>There are two major exception specification policies used in
destructors:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>No exception specification at all</p>
</li>
<li>
<p>Empty exception specification</p>
</li>
</ul>
</div>
<p>Probably, the first policy is used more widely than the second.
I would say both are used in C++ projects. For example, the C++
standard library uses both.</p>
<p>Needless to say, a <tt class="classname">Mixin&lt;T&gt;</tt>
destructor that is neutral to the exception specification policy of
<span class="type">T</span> is preferred rather than a destructor
that forces using either choice.</p>
<p>I recommend that you stop reading for a moment and try to find a
best-of-all-worlds solution. A solution that is free from the
limitation of the first version of <tt class="classname">Mixin</tt>
and that doesn't dictate a particular exception specification
policy.</p>
<p>Although you have little freedom in defining the destructor the
solution may surprise you. It is no destructor at all, that is, an
implicitly defined destructor:</p>
<pre class="programlisting">
template&lt;class T&gt;
struct Mixin : T {
};
</pre>
<p>Why is this better? To explain why, let me refer you to [1],
paragraph 15.4, bullet 13. Apart from an explanation of our case it
contains an example with multiple inheritance, which we'll analyze
later. In my informal interpretation, an implicitly defined
destructor &quot;inherits&quot; its exception specification from the base
destructor. Whatever exception specification <span class=
"type">T</span>'s destructor has so has an implicitly defined
destructor of <tt class="classname">Mixin&lt;T&gt;</tt>. Perfect,
exactly what we need!</p>
<p>You may ask how to keep it implicitly defined in real class
templates. I recommend that you use RAII wrappers, smart pointers,
C++ strings and containers wherever you can. This reduces the need
for explicitly defined destructors to very unusual cases.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e133" id="d0e133"></a>More
complexity</h2>
</div>
<p>Now it's time to solve the problem I faced. It's almost the same
as our original problem with one difference - <tt class=
"classname">Mixin</tt> has an additional base:</p>
<pre class="programlisting">
struct Base {
  // ...
};

template&lt;class T&gt;
struct Mixin : Base, T {
  // ...
};
</pre>
<p>It's clear that we can always use a nothrow destructor in
<tt class="classname">Mixin</tt>. I'd like you to analyze the case
of an implicitly defined destructor. Just remember that, on the one
hand, an implicitly defined destructor inherits exception
specifications from all its bases, and on the other hand, if any of
the base destructors is virtual, <tt class=
"methodname">~Mixin()</tt> can't have a less restrictive exception
specification. The analysis is a kind of combinatorial puzzle. You
can combine the virtuality and exception specifications of all the
destructors. Fortunately, there are only a few combinations.</p>
<p>The first case is a non-virtual destructor <tt class=
"methodname">~Base()</tt>. The analysis shows that the destructor
of <tt class="classname">Base</tt> has to have an empty exception
specification in order to define <tt class=
"methodname">~Mixin()</tt> implicitly.</p>
<pre class="programlisting">
struct Base {
  ~Base() throw();
};

template&lt;class T&gt;
struct Mixin : Base, T {
};
</pre>
<p>Although this solution dictates the exception specification
policy of the <tt class="classname">Base</tt> destructor, it's
still of interest because the resulting <tt class=
"classname">Mixin</tt> class template is neutral to the user's
exception specification policies.</p>
<p>The second case doesn't have a solution. If <tt class=
"classname">Base</tt>'s destructor is virtual we can always find a
type <span class="type">T</span> that breaks the compilation
regardless of the exception specification of <tt class=
"methodname">~Base()</tt>.</p>
<p>This was my case. I could take the destructor's virtuality out
of the base into another class responsible for polymorphic cloning
and destruction (let's say, storage management). Although it would
better fit the one class, one responsibility principle I decided to
use a quick fix solution:</p>
<pre class="programlisting">
struct Base {
  virtual ~Base();
};

template&lt;class T&gt;
struct Mixin : Base, T {
  ~Mixin() throw();
};
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e187" id=
"d0e187"></a>Conclusion</h2>
</div>
<p>I'd like to draw two conclusions. First, a summary of what has
been done.</p>
<p>Mixin classes often come with general-purpose libraries or
libraries that make no assumptions about the projects that will use
them. It's important to follow the project's rules and policies
even when a set of projects is unknown to the library author. In
this article I showed how to solve one particular problem with
respect to possible uses of your code.</p>
<p>The second conclusion is rather philosophical. Although you can
rarely find code simpler than that discussed in this article it's
worth analyzing it. I dare say there is no such thing as a little
detail in C++. Everything is important in the C++ world. If you
find an interesting note on a C++ feature or some side effect, try
to play with it. Many C++ tricks and modern techniques were
discovered this way. Keep trying! Together we'll make a better
language.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e196" id="d0e196"></a>Reference</h2>
</div>
<div class="bibliomixed"><a name="ISO" id="ISO"></a>
<p class="bibliomixed">[ISO] ISO/IEC 14882</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
