Mohan Mohan - 2 months ago 9x
C++ Question

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

There is a STL

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 ( simply says

Returns: the previous value of

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


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.