Boost logo

Boost Users :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2005-05-08 12:41:13

Eyal Susser wrote:
> Hi,
> Boost is a really neat idea, I wish I had less trouble using it (so
> embarrasing...). Anyway, here's a streambuf class I wrote using
> IOStream :

<snip example>

> But the ouput from cout is an empty string, although when debugging I
> can see m_pBuffer being copied to.


Thanks for using the Iostreams library.

There are a few problems with you code:

The first, which you couldn't be expected to know, is that write() now returns a
streamsize value indicating how many characters were written.

Second, the character type of iostreams::source is char, not unsigned char. If
you want to use unsigned char, you can do:

    class CrIPCStreamOutput {
        typedef unsigned char char_type;
        typedef sink_tag io_category;
        /* ... */

But be warned that standard libraries may not let you instantiate a
streambuf_facade with this char_type.

Third, you should flush the stream_facade after writing to it, to make sure that
buffered data has made its way to your sink.

Fourth, the implementation of write is unsafe, since you don't check for
overflow. Writing too many characters will lead to stack corruption.

Finally, and most importantly, you declare the member variable m_pBuffer as a
*reference* to a pointer. When you pass an instance of CrIPCStreamOutput to the
streambuf_facade constructor, a copy is made, and you end up with a reference to
a temporary pointer rather than the original pointer. Declaring m_pBuffer to
have type char* fixes this.

One last point is that if you want to define a stream which writes to a
preexisting buffer, you can use an array_sink, defined in the header

    iostreams::stream_facade<iostreams::array_sink> out(buf, len);

> Thanks.


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at