Apache C++ Standard Library User's Guide

## 39.3 Connecting iostream and streambuf Objects

In Section 38.3.2 we saw how to derive a new stream class. In Section 39.2 we saw how to derive a streambuf class, and an example of how to connect the two. In this section, we'll look a little more closely at the ways the two can be connected together safely.

This connection can be attempted in two different ways:

- By deriving from a descendent of ios which does not contain a streambuf, such as istream or ostream object, and providing it with an external streambuf which is itself a derived type.

- By deriving from a descendent of ios which contains a streambuf, such as a ifstream or ofstream object.

In the first case where the stream object does not contain a buffer object, the C++ standard mandates that no parent class constructors or destructors (ios, istream, or ostream) access the stream buffer. This restriction is important, since a derivation such as the following is otherwise unsafe:

    class DerivedStreamBuf : public std::streambuf {
      // ...
    };

    class DerivedOutputStream : public std::ostream {
      public:
        DerivedOutputStream():
          std::ios(0), std::ostream(&dsb) {}        //1
        // ...
      private:
        DerivedStreamBuf dsb;
        // ...
    };

`//1` | The DerivedOutputStream constructor calls its parent constructors in the following order:

1. `ios::ios()`

2. `ios_base::ios_base()`

3. `ostream::osteram(&dsb)`

4. `DerivedStreamBuf::DerivedStreamBuf()`

Looking at this order, we can see that ios and ostream were constructed before the DerivedStreamBuf() constructor was executed. Therefore the pointer `(&dsb)` passed through the ostream constructor points to as-yet uninitialized memory, and accessing it could be catastrophic. In the case where the derived stream contains a buffer object, only the descendent that defines the buffer can access it during construction or destruction. In both cases, explicitly preventing access to the stream buffer by the base class during the construction and destruction phases prevents undefined behavior.