    <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  :: STL-style Circular Buffers By Example, Part Two</title>
        <link>https://members.accu.org/index.php/articles/383</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Design of applications and programs + Overload Journal #51 - Oct 2002</span></div>

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

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

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

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

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

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

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

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

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

                    -                        <a href="https://members.accu.org/index.php/articles/c67+194/">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;STL-style Circular Buffers By Example, Part Two</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 October 2002 22:58:12 +01:00 or Wed, 02 October 2002 22:58:12 +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>In the first part of this series [<a href=
"#Goodliffe">Goodliffe</a>] we started to look at how to implement
a template container class in the style of the C++ standard
template library (STL). The example container we're working with is
a circular buffer. We started off by writing a minimal circular
buffer class, and through a number of exercises refined this basic
class until we had a mostly STL-like container class.</p>
<p>We're still not quite there yet. By the end of this article
we'll have covered all the necessary ground, and our container
class can truly be used like any other STL container.</p>
<p>As in the previous article, the approach adopted here is to
present a number of exercises for you to perform. This is more than
a clumsy article-writing device. Experience shows that you only
really learn something when you try to actually do it. You can read
around a subject as much as you like; it's only when you pick up
tools and start applying what you've read, when the metaphorical
rubber hits the hypothetical road, that you really solidify your
knowledge. These exercises are then a good opportunity to learn in
a practical way. Put as much effort into them as you want to get
out of the article.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e29" id="d0e29"></a>So where are
we?</h2>
</div>
<p>So far we have a template container class with forward and
reverse iterators. Unlike traditional circular buffer
implementations we've provided operator[] for random access; this
is largely to provide the iterator's implementation.</p>
<p>You can download an example copy of the code this far from
<a href="http://cthree.org/pete/cbuf.html" target=
"_top">http://cthree.org/pete/cbuf.html</a>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e39" id="d0e39"></a>More
constructors</h2>
</div>
<p>Amongst the functions that we still need to implement for our
circular_buffer class are a number of constructors. As an analogue,
think about vector. It has a several useful constructors. So off we
go&hellip;</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #1</b></span></p>
<p>What operations does a C++ compiler automatically generate for a
class? How do you prevent this from happening?</p>
</div>
<p>The compiler will automatically generate</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>a default constructor, which just calls the default constructors
for the class' members and bases,</p>
</li>
<li>
<p>a default copy constructor, which performs a member-wise copy of
all data members, and</p>
</li>
<li>
<p>a default comparison operator, which performs a bitwise
comparison of two objects.</p>
</li>
</ul>
</div>
<p>Sometimes these defaults are fine and do just what we want.
Often when creating more adventurous classes (with dynamically
created data members) they're not at all suitable and we have to
provide our own, or just prevent the compiler from emitting its
defaults.</p>
<p>If we provide our own versions, the defaults are suppressed.
This is of particular note for constructors - any constructor you
provide, no matter what signature it has<sup>[<a name="d0e66" href=
"#ftn.d0e66" id="d0e66">1</a>]</sup>, will suppress the
parameterless default constructor. If you want to have a
parameterless constructor you will then have to provide it, even if
it does exactly what the compiler generated version would.</p>
<p>If you don't want to supply the operations but the compiler
generated versions are wrong, you can suppress them by declaring
the functions, but not defining them. For this to make any sort of
sense, you should declare the functions as private members of the
class.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e72" id="d0e72"></a>Constructor 1:
Copy constructor</h2>
</div>
<p>A copy constructor allows us to 'clone' objects. It allows us to
write:</p>
<pre class="programlisting">
  // for some existent circular_buffer&lt;int&gt;
  // called cbuf;
  circular_buffer&lt;int&gt; copy_of_cbuf1(cbuf);
  circular_buffer&lt;int&gt; copy_of_cbuf2 = buf;
</pre>
<p>Both of these copies are created using the copy constructor.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #2</b></span></p>
<p>What signature does the copy constructor have? Will the default
version suffice for <tt class="classname">circular_buffer</tt>? If
not, write an appropriate copy constructor.</p>
</div>
<p>We're storing data in a dynamically created array, so the
default copy constructor is not appropriate. Consider what would
happen if we wrote:</p>
<pre class="programlisting">
  {
  circular_buffer&lt;int&gt; cbuf1(100);
  circular_buffer&lt;int&gt; cbuf2(cbuf1);
  }
</pre>
<p>The default copy constructor will copy the array pointer,
<tt class="literal">array_</tt>. Now both circular buffer objects
use the same array, which is plainly nonsensical. Things get worse,
though. At the end of the block scope <tt class=
"varname">cbuf2</tt> will first be destroyed. The destructor calls
<tt class="literal">delete [] array_</tt>. It is now an ex-array.
Next the <tt class="varname">cbuf1</tt> destructor is called. It
will attempt to delete the same array which is now pushing up the
daisies, a plainly wrong operation; and one that is potentially
disastrous.</p>
<p>Our replacement copy constructor can look something like the
following:</p>
<pre class="programlisting">
  circular_buffer(const circular_buffer &amp;other)
    : array_(new value_type[other.array_size_]),
      array_size_(other.array_size_),
      head_(other.head_),
      tail_(other.tail_),
      contents_size_(other.contents_size_)
    {
      std::copy(other.begin(),
      other.end(), array_);
    }
</pre>
<p>Did you hand-roll your own loop for the copy operation? It pays
to use standard library facilities where you can. This
implementation works most of the time, but there are some lurking
problems that we'll come back to later.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e112" id="d0e112"></a>Constructor
2: Iterator-based template constructor</h2>
</div>
<p>The <tt class="classname">vector</tt> class has a nice
constructor that takes two forward iterators defining a range, as
the initial contents of the container. Although not strictly
required, we can have some of that goodness, too.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #3</b></span></p>
<p>Implement a constructor with the following signature:</p>
<pre class="programlisting">
  template &lt;class InputIterator&gt;
  circular_buffer(InputIterator from, InputIterator to);
</pre></div>
<p>Here we'll have to consider what initial size our buffer should
take. We could make this value an extra parameter, but that makes
the interface less flexible and more lumpy. We could require that
the supplied iterators are random access iterators and make some
decision based on the value of to-from. Again, this requirement
makes the code less flexible. Or we can try some other scheme.</p>
<p>It is possible to implement this constructor if we provide
another function, reserve that ensures we have a specified
capacity. The vector class has this capability. Whilst it makes a
bit more sense as a member function of vector (since by definition
vectors can grow), we can make good use of it here.</p>
<pre class="programlisting">
  template &lt;class InputIterator&gt;
  circular_buffer(InputIterator from, InputIterator to)
    : array_(new value_type[100]),
      array_size_(100),
      head_(0),
      tail_(0),
      contents_size_(0)
  {
    while (from != to) {
      if (contents_size_ == array_size_) {
        reserve(static_cast&lt;size_type&gt;(array_size_ * 1.5)); // (*)
      }
      push_back(*from);
      ++from;
    }
  }
</pre>
<p>The initial capacity value has been picked arbitrarily. I'll
leave the implementation of reserve up to you. The choice of
multiplication factor at the point marked (*) is interesting -
there has been plenty of research into this. For most situations
the value of 1.5 is practical, balancing the number of
reallocations required with the amount of 'wasted space' in the
buffer.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e136" id="d0e136"></a>Assignment
operator</h2>
</div>
<p>This differs from the copy constructor considerably, although
you might think it is doing the same job. That's because the
constructor has to correctly create and initialise an entire
object, whilst the assignment operator has to deal with an already
created object; in our case memory has already been allocated.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #4</b></span></p>
<p>What signature does an assignment operator have? Write the
assignment operator for <tt class=
"classname">circular_buffer</tt>.</p>
</div>
<p>How did you do it? Be careful about the capacity of the buffer
parameter passed and the capacity of the buffer you're assigning
to. There are two ways to implement this function. You'll probably
have written something like the following:</p>
<pre class="programlisting">
  circular_buffer &amp;operator=(const circular_buffer &amp;other) {
    clear();
    // Ensure we have enough space
    if (other.contents_size_ &gt; array_size_) {
      reserve(other.array_size_ );
    }
    // Now copy the contents across
    std::copy(other.begin(), other.end(), array_);
    head_ = 0;
    tail_ = other.size();
    contents_size_ = other.size();
  }
</pre>
<p>We'll see the 'other way' later. This little function has the
same lurking problem as the copy constructor. Can you see what it
is?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e156" id="d0e156"></a>Use an
allocator</h2>
</div>
<p>The STL containers all take an additional template parameter,
the allocator. This class type abstracts the real concerns of
allocating, using, and releasing memory. The default library
<tt class="classname">std::allocator</tt> is implemented in terms
of <tt class="literal">new</tt> and <tt class=
"literal">delete</tt>, however other platforms may provide
different views of memory, be it pooled memory, garbage collected
memory, or whatever. By using an abstract allocator interface we
can avoid worrying about this sort of implementation detail and
also gain the benefits of these kinds of facilities for free. Even
if it weren't required, it would be worth it.</p>
<p>So how do we need to modify <tt class=
"classname">circular_buffer</tt>? First we add another template
parameter with a default value. It goes at the end of the template
parameter list:</p>
<p><tt class="literal">typename Alloc =
std::allocator&lt;T&gt;</tt></p>
<p>This requires us to include the <tt class=
"literal">&lt;memory&gt;</tt> header file, which defines this
default <tt class="classname">std::allocator</tt> template class.
Now we modify our list of container class <tt class=
"literal">typedefs</tt>, thus:</p>
<pre class="programlisting">
  typedef Alloc allocator_type;
  typedef typename Alloc::value_type value_type;
  typedef typename Alloc::pointer pointer;
  typedef typename Alloc::const_pointer const_pointer;
  typedef typename Alloc::reference reference;
  typedef typename Alloc::const_reference const_reference;
  typedef typename Alloc::size_type size_type;
  typedef typename Alloc::difference_type difference_type;
</pre>
<p>Note we've added the <tt class="literal">allocator_type</tt> and
we also modified these other definitions, since the allocator now
provides us with all the correct definitions. Next, to work like
any other STL container we add a data member <tt class=
"literal">alloc_</tt> of the allocator type and, for consistency,
we also add a new member function, thus:</p>
<pre class="programlisting">
  allocator_type get_allocator() const {
    return alloc_;
  }
</pre>
<p>That's the basic stuff out of the way. Next we need to make the
constructors and destructor call the allocator functions for their
memory management, rather than new and delete. Given that the
allocator class has the following functions, try exercise #5.</p>
<pre class="programlisting">
  template &lt;class T&gt;
  class std::allocator {
  public:
    typedef T *pointer;
    typedef size_t size_type;
    pointer allocate(size_type n, /*hint parameter*/);
    void deallocate(pointer p, size_type n)
    /* ... */
  };
</pre>
<p>Note that the 'hint' parameter can be ignored for our purposes,
it defaults to zero and is usually unused. <tt class=
"literal">allocate</tt> returns space for <tt class=
"literal">n</tt> objects of type <tt class="type">T</tt>. It
doesn't initialise them. deallocate frees the memory resource, but
doesn't destroy the objects.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #5</b></span></p>
<p>Alter the constructor, destructor, and <tt class=
"literal">reserve</tt> to use the <tt class="literal">alloc_</tt>
member.</p>
</div>
<p>That's not too onerous really. However, we're beginning to see a
hint of the problem I alluded to in exercise #1 of the first
article, and this is the solution. The allocator does not
<span class="emphasis"><em>initialise</em></span> any objects in
the memory pool in the way that an array would. This is crucial.
Why? Well, it doesn't matter too much for a container of <tt class=
"literal">ints</tt>. But think about a complicated class with a
slow constructor. Creating an array of these objects is therefore a
<span class="emphasis"><em>very</em></span> slow operation; an
array initialisation will call the default constructor to create an
object at each array position. It's especially wasteful when you
consider that you'll ignore the default construction, and use
assignment to write the first value you care about to each array
element anyway.</p>
<p>That's an awful lot of wasted array effort. It also introduces
an unnecessary dependency on the <tt class=
"literal">value_type</tt>: it requires that there must be a default
constructor in order to be able to allocate the array. Now using
this 'allocator' approach we are no longer bound by this
constraint, on top of not wasting effort constructing useless
objects. Bonus!</p>
<p>However, we will need to construct and destruct each object by
hand instead. This is the price we pay. Given that there are the
<tt class="classname">std::allocator</tt> member functions below,
answer exercise #6:</p>
<pre class="programlisting">
  void construct(pointer p, const T &amp;val)
    { new (p) T(val); }
  void destroy(pointer p)
    { p-&gt;~T(); }
</pre>
<p>Note the use of <span class="emphasis"><em>placement
new</em></span> by the <tt class="literal">construct</tt>
function.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #6</b></span></p>
<p>What further <tt class="classname">circular_buffer</tt> member
functions need to be changed to use <tt class=
"literal">construct</tt> and <tt class="literal">destroy</tt>?</p>
</div>
<p><tt class="literal">push_back</tt> is the only function that
needs to create new data elements<sup>[<a name="d0e278" href=
"#ftn.d0e278" id="d0e278">2</a>]</sup>. Rather than using
assignment in this function, we call <tt class=
"literal">construct</tt>. However, we don't need to do this when
the buffer is full and we're throwing away the data at the end of
the buffer by reusing the last buffer element. In this case we only
have to assign to the element as before. <tt class=
"literal">pop_front</tt> removes elements from the container, as do
<tt class="literal">clear</tt> and the destructor (are there any
others in your implementation?). These therefore need to use
<tt class="literal">destroy</tt>. Note that it will no longer be
valid to use the <tt class="literal">std::copy</tt> algorithm as we
did before - it won't take care of the object construction for
us.</p>
<p>As a final allocator modification, we must now change <tt class=
"literal">max_size</tt>. The allocator class provides this function
itself. This is logical enough since it knows how many objects
could potentially be allocated using its memory model. We therefore
make our <tt class="literal">max_size</tt> call the
allocator's.</p>
<div class="sidebar">
<p class="title c2">Whistle-stop Tour of Exception Safety</p>
<p>This is a subtle subject that has to be approached very
carefully. We don't have the time or space to do so in this
article. So here's the nuts and bolts.</p>
<p>To be maximally useful our container classes need to be
&quot;exception safe.&quot; No one's going to argue there. But what does
<tt class="literal">exception safe</tt> actually mean? This has
been a hot topic in the C++ community for some time, and only
really recently has it been understood to a reasonable depth.</p>
<p><span class="bold"><b>Exception safe</b></span> code works
correctly no matter what exceptions come its way, for some
definition of 'correctly' (we'll define this below). There is an
additional constraint to consider when writing code like ours:
exception neutral code propagates all exceptions up to its caller;
it doesn't assume the meaning of any thrown exception and won't
consume it. This is important for our 'generic' container - the
contained objects may generate all sorts of exceptions that we
don't understand. The container user will (well, should) understand
them and it's therefore up to them to deal with these errors, not
us. That's what exceptions are good for, after all.</p>
<p>Now there are several different useful levels of exception
'safety'. They are described in terms of guarantees to the calling
code.</p>
<p>These guarantees are:</p>
<p><span class="bold"><b>Basic guarantee</b></span>: If exceptions
do occur in a function (resulting from an operation we perform, or
a call on one of our contained objects) we will not leak resources.
The container state will be consistent (i.e. it can still be used
correctly) but we'll not necessarily leave in a known state. For
example, say you have a container member function that adds 10
items to a container, and an exception propagates through the
function. We will guarantee the container is still usable, but
maybe no objects were inserted, maybe all ten were, or perhaps
every other object was added. Container iterators may have been
invalidated.</p>
<p><span class="bold"><b>Strong guarantee</b></span>: This is far
more strict than the basic guarantee. Here we ensure that if an
exception propagates through our member functions the program state
will remain completely unchanged. The object hasn't been altered,
no global variables changed, nothing. All container iterators will
therefore still be valid. In our example above, we can assert that
no objects will have been inserted into the container at all.</p>
<p><span class="bold"><b>Nothrow guarantee</b></span>: The final
guarantee is the most restrictive. We guarantee that an operation
can never ever throw an exception. If we are 'exception neutral'
then this implies that the function cannot call any function that
itself might throw.</p>
<p>Which of the guarantees you provide in your code is entirely up
to you. The more restrictive the guarantee, the more widely
(re)useable the code is. It turns out that in order to implement
the strong guarantee in your member functions you will generally
require a number of functions that provide the nothrow guarantee
(for example, see the use of swap in this article). Most notably
every destructor you write should always honour the nothrow
guarantee. Always. Otherwise all exception handling bets are
off.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e337" id="d0e337"></a>Exception
safety</h2>
</div>
<p>If our class is not exception safe, it's of no real value in the
Real World. See the sidebar for a brief description of what's
involved in writing exception safe code. We don't have the space
here to really describe the subject, but we'll take a look at what
we need to do to make our code bullet proof. As it stands it is
really not at all exception safe. In fact it's downright exception
dangerous.</p>
<p>In truth, it's a bit late in the development to be considering
exception safety. However, we really needed to have got this far to
have illustrations of the issues involved.</p>
<p>We'd like to provide at least the basic exception safety
guarantee in our member functions, and ideally we want to aim to
provide the strong guarantee in every method. Let's quickly look at
some of the reasons why our existing container is dangerous. We'll
start at the beginning: some constructors, for example, are a cause
of resource leaks.</p>
<p>Look at the copy constructor. The first thing it does is
allocate memory in the initialiser list. If this fails then a
<tt class="literal">std::bad_alloc</tt> exception is thrown and
nothing leaks. This is fine behaviour, and a good reason to put
dynamically allocated memory near the head of your list of
variables (remember that data members are initialised in the order
of the class definition, not the order you list them in the
constructor's initialiser list). None of the other assignments
might throw, so we're safe in the rest of this initialiser
list.</p>
<p>However, on entering the constructor body, we loop around
copying elements. Any of the <tt class="literal">value_type</tt>
object constructors might throw an exception. Say we get half way
through the copy loop and a constructor fails. The failure
exception propagates through our constructor (so at least we're
exception neutral here), and we leak the allocated memory. We've
also created a number of contained objects that we didn't destroy -
heaven help us if there are dangerous side effects from this
behaviour.</p>
<p>Tightening up cases like this is not actually going to be
impossible to do, since I've introduced facilities in a way that
allows exception safety (for example, separating <tt class=
"literal">front</tt> and <tt class="literal">pop_front</tt>). We'll
just have to think carefully about each member function. One of the
golden rules when writing exception safe code is that each function
should have at most one side effect, otherwise an exception safe
implementation is complicated. You can see then that writing
exception safe code does have an impact on your public API design,
you have to design it in from the start.</p>
<p>When people think about exception safety they imagine code
strewn with <tt class="literal">try/catch</tt> blocks. In fact this
is far from the truth. Our exception safe code will be practically
free of these. The basic technique we follow is to perform all
potentially dangerous activities 'off to one side' in a way that
means they'll get tidied up neatly if anything fails. Once these
dangerous activities are complete we can <span class=
"emphasis"><em>then</em></span> make the changes live using
operations that are known not to throw.</p>
<p>In order to do this we are going to need some operations that
are known not to throw. We asserted in the sidebar that our
destructor can't throw. Now enter <tt class=
"literal">swap</tt>.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #7</b></span></p>
<p>Implement a member function <tt class="literal">swap(const
circular_buffer &amp;)</tt> that is guaranteed not to throw.</p>
</div>
<p>It's not too nasty. Note that we don't bother to swap the
allocator objects. They should be identical if the <tt class=
"classname">circular_buffer</tt> types are the same.</p>
<pre class="programlisting">
  void swap(circular_buffer &amp;other)
  /* nothrow */
    {
      std::swap(array_, other.array_);
      std::swap(array_size_, other.array_size_);
      std::swap(head_, other.head_);
      std::swap(tail_, other.tail_);
      std::swap(contents_size_, other.contents_size_);
    }
</pre>
<p>Although we're providing the nothrow guarantee note that we
don't put an empty exception specification at the end of the
function signature. We should try to avoid writing these when we
can, they can add unnecessary overhead to the running code; they
are more likely to make the compiler generate much worse code than
anything better. We know the function won't throw; we don't need
the compiler to check this for us too.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #8</b></span></p>
<p>Using this <span class="emphasis"><em>perform work off to the
side then make it live</em></span> idiom, go over each member
function and modify it to become exception safe (as strictly as
possible). Do you need any <tt class="literal">try/catch</tt>
blocks at all? Look first at the simplest constructor, then the
<tt class="literal">push_back</tt> and <tt class=
"literal">pop_front</tt> methods.</p>
</div>
<p>OK, that's a big task. Let's start with the basic constructor.
It's actually already strongly exception safe. The only operation
that might throw is the memory allocation. This is fine, the
<tt class="literal">std::bad_alloc</tt> exception will propagate up
and we won't leak at all. How must you alter the other
constructors? I won't show you here, but note that you will
actually need <tt class="literal">try/catch</tt> blocks in this
case. Next, <tt class="literal">push_back</tt>:</p>
<pre class="programlisting">
  void push_back(const value_type &amp;item) {
    size_type next = next_tail();
    // no state change yet
    if (contents_size_ == array_size) {
      array_[next] = item; // (*)
      increment_head();
    }
    else {
      alloc_.construct(array_ + next, item); // (*)
    }
    increment_tail();
  }

  private:

  size_type next_tail() {
      return (tail_+1 == array_size_) ? 0 : tail_+1;
  }
</pre>
<p>How is this different? Our interest is at the points marked (*).
We move the constructions/assignments to positions above any other
state manipulation. If an exception is thrown we haven't modified
any other state. This is not quite a strong exception safety
guarantee, though: our container is now as exception safe as the
<tt class="literal">value_type</tt>'s constructor/assignment
operators. This is best we can do.</p>
<p>As a final example, we'll consider the assignment operator. We
use a neat idiom here to ensure that we are strongly exception
safe:</p>
<pre class="programlisting">
  circular_buffer &amp;operator=(const self_type &amp;other) {
    circular_buffer tmp(other);
    swap(tmp);
    return *this;
  }
</pre>
<p>Can you see how neat this is? We do all the work 'off to one
side' by creating a temporary object that looks like <tt class=
"literal">other</tt>. If that fails (based on the fact the copy
constructor is exception safe and won't leak) we will propagate the
exception, but not have altered our own state and not leaked, so we
are strongly exception safe. If it succeeds we 'make permanent' the
change using two operations that are known not to fail: <tt class=
"literal">swap</tt>, and the destructor. We swap our current state
with that of tmp so we now look as if we've been 'assigned to'.
When <tt class="varname">tmp</tt> goes out of scope it is
destroyed, taking with it our old state.</p>
<p>A lot of the other functions are adjusted in similar manners. We
don't have space to describe them all here. See my reference code
(in the <span class="bold"><b>Getting the code</b></span> section
below) for further examples.</p>
<p>The long and short of exception safety is: you can't reasonably
bolt it on after writing the code. You have to factor it into the
class' design from the start. Well written exception safe code
shouldn't need tonnes of <tt class="literal">try/catch</tt> blocks.
If it's not simple and clear to read then something's wrong.
Generally you'll find that good 'exception safe' code is not just
designed to be safe in the presence of potential exceptions at the
expense of clarity and program efficiency - it will also be
genuinely well designed and thought out code.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e456" id=
"d0e456"></a>Miscellany</h2>
</div>
<p>There are still a few loose ends we need to tie up, and then
we're done.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e461" id="d0e461"></a>Insertion
behaviour policy</h3>
</div>
<p>Currently <tt class="literal">push_back</tt> will always accept
new data, even if the circular buffer is full. It does this by
throwing away the oldest data members. Perhaps our users don't want
this behaviour.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #9</b></span></p>
<p>Make this policy decision a template parameter. How much of the
class needs to change?</p>
</div>
<p>It turns out that this is a simple change, and costs very
little. Just add a new boolean template parameter (I called it the
long winded <tt class="literal">always_accept_data_when_full</tt>
and gave it a default value of <tt class="literal">true</tt>). You
want to put this parameter before the allocator definition to
follow convention.</p>
<p>The only other change needed is minimal: You need to make the
'throw data away' operation in <tt class="literal">push_back</tt>
conditional on the value of <tt class=
"literal">always_accept_data_when_full</tt>. If it's <tt class=
"literal">false</tt> we do nothing. Since this value is known at
compile time, the if statement will be optimised away.</p>
<p>Perhaps you'd like the function to throw an exception if the
buffer is full. That's another policy decision, and I'll leave it
up to you to work out how to do it.</p>
<p>This should lead us to consider how you would use a circular
buffer in the Real World. You will know the rate at which a
producer adds data to the buffer, and the rate and frequency at
which the consumer will work. Given this information you should be
able to calculate a reasonable size for the circular buffer.
Obviously throwing away data is really a last-ditch operation, and
your use of the buffer should prevent it if at all possible, so use
the buffer carefully!</p>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e498" id="d0e498"></a>A random access
iterator</h4>
</div>
<p>We wrote a bidirectional iterator in the previous article. It's
not much work at all to make it a random access iterator, we just
need to add the following operations: <tt class="literal">+ - +=
-=</tt>, plus the following comparisons: <tt class="literal">&lt;
&gt; &gt;= &lt;=</tt>. Some of these we'd already started on.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #10</b></span></p>
<p>Convert the <tt class="literal">circular_buffer_iterator</tt>
into a random access iterator.</p>
</div>
<p>Don't forget to change the <tt class=
"literal">iterator_tag</tt>.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e523" id="d0e523"></a>Comparison</h4>
</div>
<p>It would be useful to be able to compare two <tt class=
"classname">circular_buffer</tt> classes.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #11</b></span></p>
<p>Implement <tt class="literal">operator==</tt> and <tt class=
"literal">operator!=</tt>. They only need to compare two <tt class=
"literal">circular_buffers</tt> of the same type. Should they be
member functions or free functions?</p>
</div>
<p>There is no requirement for these functions to be members of the
container class, so by conventional C++ wisdom they shouldn't be.
If your implementation required access to the private members of
the class then you introduced unnecessary coupling. There are two
ways to implement the functions: the easy way and the hard way. If
you hand coded a comparison loop then you did it the hard way. You
can avoid a lot of the work by using <tt class=
"literal">std::equal</tt>.</p>
<pre class="programlisting">
  template &lt;typename A, bool B, typename C&gt;
  bool operator==(const circular_buffer&lt;A, B, C&gt; &amp;a,
                  const circular_buffer&lt;A, B, C&gt; &amp;b) {
    return a.size() == b.size() &amp;&amp; std::equal(a.begin(), a.end(), b.begin());
  }
</pre>
<p>You can figure out <tt class="literal">operator!=</tt> from
that. There's one more operator that the vector provides, which we
can also provide:</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #12</b></span></p>
<p>Implement <tt class="literal">operator&lt;</tt> for the
<tt class="classname">circular_buffer</tt> class.</p>
</div>
<p>Again, there's an easy way and a hard way. This time the easy
way uses <tt class="literal">std::lexicographical_compare</tt>.</p>
<pre class="programlisting">
  template &lt;typename A, bool B, typename C&gt;
  bool operator&lt;(const circular_buffer&lt;A, B, C&gt; &amp;a,
                 const circular_buffer&lt;A, B, C&gt; &amp;b) {
    return std::lexicographical_compare(a.begin(),
                                        a.end(),
                                        b.begin(),
                                        b.end());
  }
</pre></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e577" id="d0e577"></a>Getting the
code</h2>
</div>
<p>Whilst I know you've been slavishly following the exercises I
know that you'll want to see my reference implementation to see how
close you came to it. Or perhaps you just want an STL style
circular buffer class and can't be bothered to write your own.</p>
<p>My <tt class="classname">circular_buffer</tt> class library is
available from <a href="http://cthree.org/pete/cbuf.html" target=
"_top">http://cthree.org/pete/cbuf.html</a>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e590" id=
"d0e590"></a>Conclusion</h2>
</div>
<p>We've now created an entire template container class. It follows
the STL style carefully. Not only does this mean that we now know
how to write STL-like containers, it also means that anyone using
this <tt class="classname">circular_buffer</tt> class can pick it
up with a minimum of hassle. It behaves in a known way, can be
accessed as most other STL containers, and it is immediately
compatible with existing STL algorithms. Perhaps you've also gained
a respect for the work that has been put into the standard C++
libraries.</p>
<p>Hopefully you've enjoyed these articles, and by stepping through
the exercises you have now picked up some useful techniques that
can be applied to other code you write. Let me know if it's been
useful.</p>
<div class="sidebar">
<p><span class="bold"><b>Exercise #13</b></span></p>
<p>Take a well deserved break.</p>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e606" id="d0e606"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Goodliffe" id="Goodliffe"></a>
<p class="bibliomixed">[Goodliffe] Pete Goodliffe, &quot;STL-style
circular buffers by example,&quot; Overload 50, August 2002, ISSN:
1354-3172.</p>
</div>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e66" href="#d0e66" id=
"ftn.d0e66">1</a>]</sup> Actually, modulo any tempate
constructors.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e278" href="#d0e278" id=
"ftn.d0e278">2</a>]</sup> That is, if you implement the new
constructors and assignment operator in terms of push_back, which
is a very reasonable design.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
