    <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</title>
        <link>https://members.accu.org/index.php/journals/389</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 #50 - Aug 2002 + 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/c195/">50</a>
                    (7)
<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/c195-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c195+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;STL-style Circular Buffers By Example</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 August 2002 22:58:28 +01:00 or Fri, 02 August 2002 22:58:28 +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>I've always found that you don't learn anything until you try to
actually do it. In this article I provide a practical chance to
learn some new C++ knowledge. If you fancy getting your hands dirty
here then you might pick up some valuable new techniques. This is a
gentle introduction to writing robust STL-like generic
containers.</p>
<p>Recently I needed a <i class="firstterm">circular buffer</i> to
implement some low level logic. These data structures aren't
exactly complicated to write, but it got me thinking. That's a
dangerous thing at the best of times. I've never written an
STL-style container before, and I'd never come across an STL-like
circular buffer<sup>[<a name="d0e27" href="#ftn.d0e27" id=
"d0e27">1</a>]</sup>.</p>
<p>With a somewhat gung-ho attitude I began to implement an
STLcompatible circular buffer class. I'm not going to say I've got
it perfect but I present here my journey of discovery in the hope
that it will be useful. You have the chance to cover a lot of the
same ground I did since I'll take us on this journey via a few
&quot;exercises&quot; - just a little something to get you thinking.</p>
<p>Put as much effort into the exercises as you like. As with so
many things, the more effort you put into it, the more you'll get
out at the end.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e35" id="d0e35"></a>What is a
circular buffer?</h2>
</div>
<p>Before we delve into the murky depths of the STL let's take a
quick refresher course in circular buffers.</p>
<p>There are a number of fundamental data structures in computer
science. The <i class="firstterm">array</i> is about as basic as it
comes, its implementation essentially requires a base pointer to
some allocated memory, and an index into it. You could perhaps
argue a <i class="firstterm">stack</i> is even more basic: if you
don't want to check for the location of top of the stack you only
need a single &quot;current location&quot; pointer. Textbook examples of
stack code are generally implemented in terms of an array,
though.</p>
<p>Coming hot on the heels of these two faithful friends is the
good old circular buffer. It looks like an array but has FIFO
consumption semantics<sup>[<a name="d0e50" href="#ftn.d0e50" id=
"d0e50">2</a>]</sup>, can smell really quite like an array, but
gives the pretence of being infinite in size. How does it do this?
This is where the circular bit comes into play. The logical buffer
is considered to 'wrap around' the physical array it is implemented
inside. The 'head' and 'tail' of the buffer chase each other around
the implementation array.</p>
<p>The following diagram may help envision this.</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/goodliffe%20circular%20buffer.png" align="middle"></div>
<p>Circular buffers have a number of uses. For example, device
drivers that constantly receive data (like a serial port), and need
to buffer it often use circular buffers - acting as a data
'producer' for the client code. It is the client's responsibility
to consume the data about as fast as it is produced to ensure that
no data is lost. This makes reasoning about the data exchange
easier. The circular buffer helps here since the producer (driver)
only needs to worry about adding data to the end of the circular
buffer, whilst the consumer only needs to worry about reading from
the front.</p>
<p>A simple C++ circular buffer class interface would look like
this. For the moment, let's presume that the buffer just stores
<tt class="type">int</tt>s:</p>
<pre class="programlisting">
class simple_cbuf {
  public:
    enum { default_size = 100; };
    explicit simple_cbuf(size_t size =
                         default_size);
    ~simple_cbuf();
    size_t size() const;
    bool   empty() const;
    int    top() const; /* see below */
    void   pop();
    void   push(int new_value);
  private:
    /* whatever you want */
};
</pre>
<p>Note that here we separate <tt class="methodname">top</tt> and
<tt class="methodname">pop</tt>. Some implementers might like a
single atomic top-and-pop function. However, this approach keeps
consistency with the STL <tt class="classname">vector</tt>-like
interface which will help later on. There is also a practical
reason to split the two functions - it makes exception safety
issues easier to reason about. More on this later.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #1</b></span><br>
Implement this simple class API. At this stage it's OK to store<br>
the data in a dynamically created array<sup>[<a name="d0e82" href=
"#ftn.d0e82" id="d0e82">3</a>]</sup>.</p>
</div>
<p>Hopefully that exercise made you wonder what to do in push when
the buffer is full. If we want to &quot;pretend&quot; to be of infinite size
then somewhere along the way some data will have to be thrown away.
There are two choices:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>throw away the new data, and leave the <tt class=
"classname">simple_cbuf</tt> state unchanged, or</p>
</li>
<li>
<p>throw away the data at the 'front' of the circular buffer and
replace it with the new 'end' data.</p>
</li>
</ul>
</div>
<p>In practice the latter case is often required - this is the
whole point of the circular buffer (the first method is really
rather like a fixed size array, after all). It might be nice to
provide a policy option to select what behaviour you want. Our
final solution will allow us to make this choice with no extra
cost.</p>
<p>Did you think about copy construction and copy assignment?
Basing our implementation on a dynamically created array will mean
that we'll need to provide correct behaviour for these two members.
They must be either declared as private and unimplemented, or added
to the class' public API.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e102" id="d0e102"></a>Random
access?</h2>
</div>
<p>Now here's an interesting usage question, the above minimal
interface doesn't allow us to randomly access the buffer. In this
respect it just looks like a stack. This isn't too hard to do,
though - try exercise two.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #2</b></span><br>
Implement an <tt class="methodname">operator[]</tt> for the
<tt class="classname">simple_cbuf</tt>.</p>
</div>
<p>This should be fairly simple to do, there's just one thing to
watch out for. For maximum usefulness we need to provide two
versions of <tt class="methodname">operator[];</tt> one 'normal'
version for non-const objects, and one for <tt class=
"literal">const</tt> objects. This allows us to provide assignment
into the <tt class="classname">simple_cbuf</tt>. You should end up
with two functions whose signatures are thus:</p>
<pre class="programlisting">
int       &amp;operator[](size_t);
const int &amp;operator[](size_t) const;
</pre>
<p>This is the canonical form of these functions, although for an
int-holding container we perhaps don't need to pass a const
int&amp; from the <tt class="methodname">const operator[]</tt>, we
could get away with just an <tt class="type">int</tt> return type.
We'll stick with this because it's good practice.</p>
<p>Now we have something that looks a quite like an array, but with
more usual circular buffer FIFO characteristics.</p>
<p>With this kind of behaviour is this data structure genuinely
useful? Does it have any benefits over a plain array? Actually it
can be very useful, but it would be limited to a smaller set of
problems than something like, say, an STL <tt class=
"classname">vector</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e147" id="d0e147"></a>Make it
generic</h2>
</div>
<p>So we now have a pretty complete <tt class=
"classname">simple_cbuf</tt> class, but it only works for
<tt class="type">int</tt>s. The final introductory step is to make
it generic.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #3</b></span><br>
Add a line <tt class="literal">template&lt;typename T&gt;</tt> to
the beginning of<br>
the class definition and modify the code accordingly.<br>
How much of the public API do you need to modify?</p>
</div>
<p>This really isn't too onerous. Obviously if you were thinking
about separate <tt class="filename">cbuf.h</tt> and <tt class=
"filename">cbuf.cpp</tt> files you now want to munge the function
definitions into the header file, but it's largely a case of
selectively replacing of <tt class="type">int</tt>s with <tt class=
"type">T</tt>s.</p>
<p>The second question: &quot;How much of the public API do you need to
modify?&quot; is worth considering. For a simple integer circular buffer
you can pass parameters to <tt class="methodname">push</tt> by
value. However since <tt class="type">T</tt> could now be any class
type you really want to pass by <tt class="type">const&amp;</tt>.
Also should top return a <tt class="type">T</tt> by value, or by
<tt class="type">const&amp;</tt>? The latter makes more sense,
since it prevents clients from being stupid with a temporary object
by writing something like:</p>
<pre class="programlisting">
cbuf.top() = T(); // meaningless; no part
    // of cbuf would be modified by this,
    // despite what it looks like
</pre>
<p>Our choice of return type for <tt class=
"methodname">operator[]()</tt> const is now also vindicated.</p>
<p>So now we have seen what a circular buffer is, how to use it and
how to implement a fairly basic example case. The rest can't be
that hard, can it?</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e207" id="d0e207"></a>Moving
towards the STL style</h2>
</div>
<p>Now we'll start to write an STL style container that's based on
the class we've developed above. I'm going to presume at this point
that you're familiar with using the STL and its definitions of
container class interfaces<sup>[<a name="d0e212" href="#ftn.d0e212"
id="d0e212">4</a>]</sup>. What do we need to provide to make this
circular buffer class more STL-like?</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>standardised <tt class="literal">typedef</tt>s like <tt class=
"type">value_type</tt> etc,</p>
</li>
<li>
<p>standardised API names,</p>
</li>
<li>
<p>iterators (forward, reverse, random access),</p>
</li>
<li>
<p>use allocators for memory operations, and</p>
</li>
<li>
<p>to be maximally useful, exception safe (and also exception
neutral)</p>
</li>
</ul>
</div>
<p>We'll start adding this functionality in stages and consider
what we're doing at each point.</p>
<p>Our implementation will start off template based, using a
dynamically created array as the internal data storage
implementation. So here's the initial framework of our class, not
yet worrying about any of the above list of items to include. We'll
flesh it out as we go along:</p>
<pre class="programlisting">
template &lt;class T&gt;
class circular_buffer {
  public:
    explicit circular_buffer(
        size_t capacity = 100)
        : array_(new T[capacity]),
          array_size_(capacity),
          head_(0), tail_(0),
          contents_size_(0) {}
    ~circular_buffer()
        { delete [] array_; }
    /* ... */
  private:
    T      *array_;
    size_t  array_size_;
    size_t  head_;
    size_t  tail_;
    size_t  contents_size_;
};
</pre>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e247" id="d0e247"></a>Step 1: Some
standard type definitions</h3>
</div>
<p>To work with STL components we need to provide these definitions
in the public API of our class<sup>[<a name="d0e252" href=
"#ftn.d0e252" id="d0e252">5</a>]</sup>:</p>
<pre class="programlisting">
value_type      // The type of the
                //  container's elements.
Pointer         // A pointer to the
                //  element type.
const_pointer   // As above, but const.
Reference       // A reference to the
                //  element type.
const_reference // As above, but const. 
size_type       // The type used to index
                //  into the container.
difference_type // The type of the result
                //  of subtracting two
                //  container iterators.
</pre>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #4</b></span><br>
What should they be?</p>
</div>
<p>No rocket science yet. At this stage, my choice was:</p>
<pre class="programlisting">
typedef T          value_type;
     /* T is template param */
typedef T         *pointer;
typedef const T   *const_pointer;
typedef T         &amp;reference;
typedef const T   &amp;const_reference;
typedef size_t     size_type;
typedef ptrdiff_t  difference_type;
</pre>
<p>Now the original framework code can be slightly modified - I'll
change the variable and parameter types from <tt class=
"type">size_t</tt> to <tt class="type">size_type</tt> and for
<tt class="literal">array_</tt> from <tt class="type">T*</tt> to a
<tt class="type">value_type*</tt>. Is this too picky? No, it will
aid future maintainability. If one of these definitions needs
changing later (hint - it will) then the change can be made in one
place and apply to all the code we've written.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e285" id="d0e285"></a>Step 2:
Appropriate function names and implementations</h3>
</div>
<p>Now, in the <tt class="classname">vector</tt> API we have
<tt class="methodname">front</tt>, <tt class=
"methodname">back</tt>, <tt class="methodname">push_back</tt>,
<tt class="methodname">pop_back</tt> and <tt class=
"methodname">clear</tt>. We'd like those (or something akin to
them). We'll clearly not provide <tt class=
"methodname">pop_back</tt>, instead there will be <tt class=
"methodname">pop_front</tt> for good circular buffer measure.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #5</b></span><br>
How would you implement these?<br>
Take care over function signatures to ensure maximal<br>
efficiency in the light of template types.</p>
</div>
<p><tt class="methodname">front</tt> and <tt class=
"methodname">back</tt> are pretty simple. There's just one thing to
watch out for here, appropriate <tt class="literal">const</tt> and
non-<tt class="literal">const</tt> versions:</p>
<pre class="programlisting">
reference front()
               { return array_[head_]; }
reference back()
               { return array_[tail_]; }
const_reference front() const
               { return array_[head_]; }
const_reference back() const
               { return array_[tail_]; }
</pre>
<p>What happens if you call these when the circular buffer is
empty? It's an invalid call and we define this to result in
<span class="emphasis"><em>unspecified behaviour</em></span>. We
could provide a 'safe' version of the <tt class=
"classname">circular_buffer</tt> class later on that does checking,
but we don't want to be burdened by it unnecessarily. It is up to
the user to call us in a consistent and valid manner.</p>
<p>The <tt class="methodname">clear</tt> member function is also
reasonably simple:</p>
<pre class="programlisting">
void clear() 
  { head_ = tail_ = contents_size_ = 0; }
</pre>
<p>In order to implement the final two functions, I'd define these
private helper functions:</p>
<pre class="programlisting">
void increment_tail() {
  ++tail_;
  ++contents_size_;
  if (tail_ == array_size_) tail_ = 0;
}
void increment_head(){
  // precondition: !empty()
  ++head_;
  -contents_size_;
  if (head_ == array_size_) head_ = 0;
}
</pre>
<p>Now <tt class="methodname">push_back</tt> and <tt class=
"methodname">pop_front</tt> can be implemented along the following
lines. It's actually a reasonably verbose <tt class=
"methodname">push_back</tt> implementation, but will show exactly
how we reason about the contents of the circular buffer, and where
<tt class="varname">head_</tt>, <tt class="varname">tail_</tt>, and
<tt class="varname">contents_size_</tt> fit into the equation:</p>
<pre class="programlisting">
void push_back(const value_type &amp;item) {
  if (!contents_size_) {
    array_[head_] = item;
    tail_ = head_;
    ++contents_size_;
  }
  else if (contents_size_ != array_size_)
  {
    increment_tail();
    array_[tail_] = item;
  }
  else {
    // We always accept data when full
    // and lose the front()
    increment_head();
    increment_tail();
    array_[tail_] = item;
  }
}
void pop_front() { increment_head(); }
</pre>
<p>Again with <tt class="methodname">pop_front</tt> we'll insist
the user only calls the function when it is semantically valid,
making our life a lot easier. Don't think we're being unnecessarily
lazy here; this is exactly what the standard <tt class=
"classname">vector</tt> does!</p>
<p>For the record, can we coalesce some of that sloppy <tt class=
"methodname">push_back</tt> logic above? Indeed we can, if we apply
a few other minor modifications to the class:</p>
<pre class="programlisting">
void push_back(const value_type &amp;item) {
  increment_tail();
  if (contents_size_ == array_size_)
    increment_head();
  array_[tail_] = item;
}
</pre>
<p>That looks nicer. To get here we have removed the special case
of an empty buffer. To cope with this we need to set the member
variables to a different pre-ordained state. The constructor and
<tt class="methodname">clear</tt> should initialise <tt class=
"varname">tail_</tt> and <tt class="varname">contents_size_</tt> to
zero as before. <tt class="varname">head_</tt> should now though be
set to <tt class="literal">1</tt>.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e408" id="d0e408"></a>Step 3: More
simple functions</h3>
</div>
<p>You won't get many points for these simple functions, but they
make for a consistent container API.</p>
<div class="sidebar">
<div class="literallayout">
<p><span class="bold"><b>Exercise #6</b></span><br>
Implement the following simple functions:</p>
</div>
<pre class="programlisting">
size_type size() const;
size_type capacity() const;
bool empty() const;
size_type max_size() const;
</pre></div>
<p>They're all self explanatory except for <tt class=
"methodname">max_size</tt>. This function returns the largest
possible size of the container. A reasonable example implementation
is:</p>
<pre class="programlisting">
size_type max_size() const {
  return size_type(-1) /
                 sizeof(value_type);
}
</pre>
<p>An alternative is to use <tt class=
"function">std::numeric_limits&lt;size_type&gt;::max()</tt>.
However, this requires that we include the <tt class=
"filename">&lt;limits&gt;</tt> header file and we'll avoid that for
the moment.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e435" id="d0e435"></a>Step 4: Random
access</h3>
</div>
<p>We want to implement iterators, and this requires that we
provide general access to our circular buffer via <tt class=
"methodname">operator[]</tt>. We implemented this in exercise #2,
so we need to move this over to our new class. However, to be more
thorough and more <tt class="classname">vector</tt>-like we can
observe that vector also provides the at function, that provides a
checked access, whilst the <tt class="methodname">operator[]</tt>
only provides unchecked access.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #7</b></span><br>
Implement both <tt class="literal">const</tt> and non-<tt class=
"literal">const</tt> forms of<br>
<tt class="methodname">operator[]</tt> and at for <tt class=
"classname">circular_buffer</tt>.</p>
</div>
<p>Now our circular buffer is randomly accessible we can move
onwards and upwards...</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e468" id="d0e468"></a>Step 5:
Implement an iterator</h3>
</div>
<p>In exercise #2 we said that it was debatable whether the
<tt class="methodname">operator[]</tt> functions should have been
added to the circular buffer class. Certainly in a traditional
circular buffer design you wouldn't have them. However, part of the
point of this whole exercise is to learn how to write a generic
container that can be iterated over, which will make it compatible
with standard library algorithms. Because of this we <span class=
"emphasis"><em>should</em></span> be able to randomly access data
in the circular buffer.</p>
<p>If you hold to the view that buffer data may be read, but may
not be written by random access, then you will only implement the
<tt class="literal">const</tt> version of <tt class=
"methodname">operator[]</tt> and only provide a <tt class=
"classname">const_iterator</tt>. However, for the full STL
&quot;experience&quot; we'll allow the non-<tt class="methodname">const
operator[]</tt> and provide both mutable types of iterators.</p>
<p>We'll start off by considering how to write a non-<tt class=
"literal">const</tt> forward iterator, and work up from there.</p>
<p>The simplest example of an iterator would be for an array - the
iterator type would be a simple pointer. The &quot;end&quot; iterator would
be a pointer to one-past-the-end of the array. We can't simply use
a pointer to iterate over our circular buffer, so we'll have to
define our own class type. For obvious reasons we'll call it
<tt class="classname">circular_buffer_iterator</tt>.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #8</b></span><br>
What data members does <tt class=
"classname">circular_buffer_iterator</tt><br>
require?</p>
</div>
<p>To iterate over a <tt class="classname">circular_buffer</tt>
effectively we only need to know which the <tt class=
"classname">circular_buffer</tt> is and at what index we currently
stand. However, <tt class="classname">circular_buffer</tt> is a
template type so how can we refer to it? We'll make the iterator a
template class too, dependant on the type of the circular buffer.
We could make it dependant on the <tt class="type">value_type</tt>
of the circular_buffer, but we choose not to. Why? Because later on
we'll add more template parameters to the container class and that
would make the alternative iterator implementation prohibitively
complex.</p>
<p>Should we store a pointer or reference to the <tt class=
"classname">circular_buffer</tt>? They are equivalent for these
purposes - if a reference became stale the iterator could be
considered to have become invalid anyway, using the iterator would
then be invalid. However, since we need to implement <tt class=
"methodname">operator==</tt> for the iterator class, it's easier to
compare pointers, so that's what we'll choose.</p>
<p>This means we start off with a class like this:</p>
<pre class="programlisting">
template&lt;typename T&gt;
      // T is circular_buffer type
class circular_buffer_iterator {
  public: 
    typedef T cbuf_type;
    circular_buffer_iterator(
         cbuf_type *b, size_t start_pos)
         : buf_(b), pos_(p) {}
      /* ... */
  private:
    cbuf_type *buf_;
    size_t     pos_;
};
</pre>
<p>There's a lot of operations we need to define for this class.
But first, we need to add the appropriate <tt class=
"literal">typedef</tt> and functions into <tt class=
"classname">circular_buffer</tt> class to meet STL
requirements<sup>[<a name="d0e545" href="#ftn.d0e545" id=
"d0e545">6</a>]</sup>:</p>
<pre class="programlisting">
typedef
   circular_buffer_iterator&lt;self_type&gt;
   iterator; 
iterator begin()
    { return iterator(this, 0); }
iterator end()
    { return iterator(this, size()); }
</pre>
<p>We'll have appropriately defined <tt class=
"type">self_type</tt>, naturally.</p>
<p>STL iterators are required to define a number of <tt class=
"literal">typedef</tt>s. These are:</p>
<pre class="programlisting">
iterator_category // See below.
value_type        // Type of element
                  //  iterator 'points
                  //  to'.
size_type         // Container index
                  //  type.
difference_type   // Container difference
                  //  type.
Pointer           // Type of a pointer to
                  //  element.
const_pointer     // As above, but const.
Reference         // Type of a reference
                  //  to element.
const_reference   // As above, but const.
</pre>
<p>Don't they look suspiciously like the <tt class=
"literal">typedef</tt>s in the container class? Does that give you
a clue how to implement them?<sup>[<a name="d0e571" href=
"#ftn.d0e571" id="d0e571">7</a>]</sup> But what's that <tt class=
"type">iterator_category</tt> definition for? This is a type as
defined by the C++ standard that defines what operations are valid
on the iterator. We can choose what kind of iterator to provide,
and define it here. The simplest is a <span class=
"emphasis"><em>forward iterator</em></span>, the most comprehensive
a <span class="emphasis"><em>random access iterator</em></span>.
For the moment we'll compromise: our iterator will be a
<span class="emphasis"><em>bidirectictional iterator</em></span>,
so we'll set this to <tt class=
"classname">bidirectional_iterator_tag</tt><sup>[<a name="d0e598"
href="#ftn.d0e598" id="d0e598">8</a>]</sup>.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #9</b></span><br>
What operations should an iterator support? How do you<br>
implement them?</p>
</div>
<p>Obviously, we need to dereference an iterator. That means we
need to provide an implementation of <tt class=
"methodname">operator*</tt> and <tt class=
"methodname">operator-&gt;</tt>. They're not hard. The following
code does the trick:</p>
<pre class="programlisting">
T &amp;operator*()
        { return (*buf_)[pos_]; }
T *operator-&gt;()
        { return &amp;(operator*()); }
</pre>
<p>The other operations on an iterator type are reasonably simple.
We don't have to do too much error checking; remember that
incrementing an iterator past <tt class="methodname">end()</tt> is
invalid and results in undefined behaviour.</p>
<div class="sidebar">
<div class="literallayout">
<p><span class="bold"><b>Exercise #10</b></span><br>
For a bidirectional iterator we need to implement the follow<br>
functions. How would you do this?</p>
</div>
<pre class="programlisting">
self_type &amp;operator++()
self_type operator++(int)
self_type &amp;operator-()
self_type operator-(int)
</pre>
<div class="literallayout">
<p>These are some simple random access iterator operations that<br>
we can also implement here. How will you provide these?</p>
</div>
<pre class="programlisting">
self_type operator+(difference_type n)
self_type &amp;operator+=(difference_type n)
self_type operator-(difference_type n)
self_type &amp;operator-=(difference_type n)
bool operator==(const self_type &amp;other) const
bool operator!=(const self_type &amp;other) const
</pre>
<div class="literallayout">
<p>What are the differences between the two forms of<br>
<tt class="methodname">operator++</tt> and <tt class=
"methodname">operator-</tt>?</p>
</div>
</div>
<p>Answering the last question first, remember that these two forms
are pre- and post-increment/decrement (respectively). Take care
over the canonical forms of all of the above functions. As a guide,
here are the implementations of <tt class=
"methodname">operator++</tt>, <tt class="methodname">operator+</tt>
and <tt class="methodname">operator+=</tt> (for a suitable
definition of self_type):</p>
<pre class="programlisting">
self_type &amp;operator++() {
  ++pos;
  return *this;
}
self_type operator++(int) {
  self_type tmp(*this);
  ++(*this);
  return tmp;
}
self_type operator+(difference_type n)
{
  self_type tmp(*this);
  tmp.pos_ += n;
  return tmp;
}
self_type &amp;operator+=(difference_type n) {
  pos_ += n;
  return *this;
}
</pre>
<p><tt class="methodname">operator==</tt> and <tt class=
"methodname">operator!=</tt> are made easier since we decided to
store pointers to the <tt class="classname">circular_buffer</tt>
and not references.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e664" id="d0e664"></a>Step 6: A
<tt class="literal">const</tt> iterator</h3>
</div>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #11</b></span><br>
How different from the above iterator interface is a <tt class=
"literal">const</tt><br>
iterator interface?</p>
</div>
<p>The answer is, not much. We'll need to point to a const
<tt class="classname">circular_buffer</tt>, return <tt class=
"literal">const</tt> references to the buffer data when deferenced,
and that's about it. It seems a little bit of a shame to rewrite
another class that is almost identical to the one we already have.
To prevent too much duplicated code we can factor out the
commonality. How best do we do this? Write one class and move out
the policy decisions to template arguments.</p>
<p>Unfortunately it's not quite as simple as defining the existing
template parameter <tt class="type">T</tt> (circular buffer type)
to be a <tt class="literal">const</tt> <tt class=
"classname">circular_buffer</tt>. We need to determine the type of
reference to return (i.e. choose between <tt class=
"classname">circular_buffer</tt>'s <tt class="type">reference</tt>
or its <tt class="type">const_reference</tt> types). We can make
this another parameter, and we're <span class=
"emphasis"><em>almost</em></span> there. What we've got now is:</p>
<pre class="programlisting">
template&lt;typename T,
       typename elem_type =
       typename T::value_type&gt;
class circular_buffer_iterator {
  public: 
    /* ... */
    elem_type &amp;operator*();
    elem_type *operator-&gt;();
};
</pre>
<p>Providing a default type for this means that our original
<tt class="type">circular_buffer::iterator</tt> <tt class=
"literal">typedef</tt> is still correct. The rest is the same, even
the definitions of these operators. To create a const iterator we
just need to instantiate the iterator class with</p>
<pre class="programlisting">
&lt;const circular_buffer, const circular_buffer::value_type&gt;
</pre>
<p>There is only one problem left with our reverse iterator
implementation. You need to be able to convert from a non-const
iterator to a <tt class="literal">const</tt> one so we can write
code like:</p>
<pre class="programlisting">
circular_buffer::const iterator i =
                            cbuf.begin();
</pre>
<p>where <tt class="varname">cbuf</tt> is a non-<tt class=
"literal">const</tt> circular buffer. The path of least resistance
for implementing this is to add another template parameter
<i class="parameter"><tt>T_nonconst</tt></i> (putting it after
<tt class="type">T</tt>), which is the same as template parameter
<tt class="type">T</tt>, but without any const qualification. We
can then write the following few lines and get the desired
conversion:</p>
<pre class="programlisting">
circular_buffer_iterator (
      const circular_buffer_iterator&lt;
         T_nonconst, T_nonconst,
         dir, typename
         T_nonconst::value_type&gt;
      &amp;other )
  : buf_(other.buf_), pos_(other.pos_) {}
  friend class
    circular_buffer_iterator&lt;
         const T, T,
         dir, const elem_type&gt;;
</pre>
<p>Naturally, we now add a <tt class="literal">typedef</tt>
definition for <tt class="classname">reverse_iterator</tt> to the
<tt class="classname">circular_buffer</tt> class. We can now do
most normal iterator operations. One more thing to consider for
now...</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e758" id="d0e758"></a>Step 7: A
reverse iterator</h3>
</div>
<p>If we can iterate forwards then we can also iterate backwards.
Conventional STL containers provide this functionality, returning
<i class="firstterm">reverse iterators</i> from their <tt class=
"methodname">rbegin</tt> and <tt class="methodname">rend</tt>
member functions. A reverse iterator starts (logically enough) at
the last element in the container. Every time you increment it, it
will actually step <span class="emphasis"><em>back</em></span> one
element. <tt class="methodname">rend</tt> points to the
'one-past-the-front' element of the container. Providing reverse
iterators means we can apply all the standard algorithms backwards
as well as forwards without writing any new algorithm code.</p>
<div class="sidebar literallayout">
<p><span class="bold"><b>Exercise #12</b></span><br>
How would you modify the iterator class we've already made<br>
to create a reverse iterator?</p>
</div>
<p>There's two ways to do this. The easy way, or the hard way.
Choose! I took the high road, but we don't have to when the low
road is perfectly acceptable. At first I created my own reverse
iterator class in a similar manner to the const iterator; cunning
additional template parameters.</p>
<p>However, to make our life that little bit easier the STL
provides an iterator adaptor that automatically creates a reverse
iterator for you, based on your forward iterator implementation. I
noticed that just a little bit too late, although I was pretty
happy that my reverse iterator looked so much like the standard
library one! Using this STL facility is by far the better option.
It is likely to contain fewer bugs (hopefully none), and will more
likely behave in a manner our users expect.</p>
<p>So how do we use this STL magic? Just add the following lines to
the <tt class="classname">circular_buffer</tt> <tt class=
"literal">typedef</tt>s:</p>
<pre class="programlisting">
typedef
    std::reverse_iterator&lt;iterator&gt;
    reverse_iterator;
typedef
    std::reverse_iterator&lt;const_iterator&gt;
    const_reverse_iterator;
</pre>
<p>That's it. If you really want to understand what's going on in
the <tt class="classname">reverse_iterator</tt> template class,
think how you would implement your own version. Consider how you
would represent <tt class="methodname">rend()</tt> bearing in mind
that our index type (<tt class="type">size_type</tt>) is unsigned
and the one-past-the-beginning index would be -1. Solve that
conundrum and you've done the hard work of a reverse iterator
implementation.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e808" id="d0e808"></a>What have we
achieved?</h2>
</div>
<p>So far we have created a circular buffer class that looks pretty
similar in API and usage conventions to the other STL containers.
This means that any C++ programmer can pick the class up and use it
pretty much immediately with no steep learning curve. It also means
that, thanks to the iterators we have provided, the class can
immediately be used with all the standard library algorithms
currently available.</p>
<p>Of course, there's still more work we need to do&hellip;</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e815" id="d0e815"></a>Next
time</h2>
</div>
<p>We'll look into working with standard library allocators and
knitting up exception safety issues. There are one or two more
functions to provide which we'll look at too - look over what we've
done and see if you can work out what's left.</p>
</div>
<div class="footnotes"><br>
<hr class="c3" width="100">
<div class="footnote">
<p><sup>[<a name="ftn.d0e27" href="#d0e27" id=
"ftn.d0e27">1</a>]</sup> There may be a good reason; it's a moot
point whether such a data structure is a genuinely useful thing.
Still, why let that stop us?</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e50" href="#d0e50" id=
"ftn.d0e50">2</a>]</sup> FIFO: First In First Out. You can only add
data to the end of the &quot;array&quot; and consume from the &quot;front&quot;.
Imagine sending ping pong balls down a thin vertical tube, the
order you get them out at the bottom is the order you put them in
at the top.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e82" href="#d0e82" id=
"ftn.d0e82">3</a>]</sup> If you don't know why this might be a
problem later on don't worry - you'll find out soon enough. (Well,
in the second part of this series.)</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e212" href="#d0e212" id=
"ftn.d0e212">4</a>]</sup> If you want to view an online reference
of the STL interfaces, there is one publicly available from
<a href="http://www.sgi.com/tech/stl/" target=
"_top">http://www.sgi.com/tech/stl/</a>.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e252" href="#d0e252" id=
"ftn.d0e252">5</a>]</sup> Actually, there's more (including
iterator definitions) but we'll start here.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e545" href="#d0e545" id=
"ftn.d0e545">6</a>]</sup> We'll also have to add a <tt class=
"classname">const_iterator</tt> definition, but we'll come to that
in the next section.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e571" href="#d0e571" id=
"ftn.d0e571">7</a>]</sup> Whilst I <tt class="literal">typedef</tt>
these here based on the container <tt class=
"literal">typedef</tt>s, you can alternatively make your life
easier by using the <tt class="classname">std::iterator</tt>
template class definition.</p>
</div>
<div class="footnote">
<p><sup>[<a name="ftn.d0e598" href="#d0e598" id=
"ftn.d0e598">8</a>]</sup> Don't worry, we'll make this a full
random access iterator in the next article.</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
