Search code examples
c++stlstreambuf

rdbuf(...) returns a pointer -- who owns the buffer pointed to?


There is a STL <ios> library function

streambuf* std::basic_ios::rdbuf (streambuf* sb);

This function can be used to change the stream buffer associated with a stream. If you use this, it returns a pointer to the streambuf that was previously in use. It's not clear who 'owns' the pointer or what its lifetime is. The standard (27.5.5.3/5) simply says

Returns: the previous value of rdbuf().

which is not very informative. Are there any guarantees about how long this pointer is valid for? Should the calling code delete the pointer once it's done with it?


Solution

  • The buffer is owned by whoever originally installed the buffer into the stream object. A stream object comes with an internal buffer, and a default-constructed stream object uses it by default.

    So, unless your code explicitly installed a non-default buffer, using the rdbuf() method, the answer is that the buffer is valid as long as the stream object exists.

    If you did not install the buffer, you should obviously not delete it.