Examples are shown here with the realative snippt, full working examples can be found in the examples directory.
The examples use the following terms;
- Stream: the stream object,
std::istream
,std::ostream
- Managed:
- Buffer: the
std::streambuf
object
- Table of Contents
- Unique/Shared Stream
- Set a streambuf
- Unmanged stream via raw pointer
- Force switch to managed streambuf
- Detect and delete unmanaged streambuf
- Using the derived streambuf
- Unique Stream
- Shared Stream
To set the streambuf object, simply either wrap the pointer in a smart pointer
or pass the pointer to the smart_stream
ctor.
unique_stream output(new stringstream());
unique_ptr<streambuf> ptr(new stringstream());
unique_stream output2(ptr);
shared_stream output(new stringstream());
shared_ptr<streambuf> ptr(new stringstream());
shared_stream output2(ptr);
Useing a raw std::streambuf
pointer it is possible to use a smart_stream
type as a regular i/o stream.
stream.rdbuf(new filebuf());
Make the smart_stream set the internal streambuf to the manged one. Also look at 2-4 for deleting the previous ptr.
stream.rebind();
There is always the chance that some code that has access to the smart stream treats it as a standard stream and changes the underlying streambuf . If this occurs the manged streambuf is still intact until the end of the smart stream.
The pointer can be re-bound and the un-manged one delted, or it could just be checked and left alone.
/* rebind first is optional */
auto ptr = stream.rebind();
if (ptr != stream.rdbuf())
/* pointers are differnt */
delete ptr;
When using smart streams the streambuf is used as a std::streambuf
type.
This means that any additional funciality is lost when accessing the
streambuf directly via smart streams. To use the derived streambuf without
downcasting, the derived streambuf must kept externally.
example: external_streambuf.cpp
shared_ptr<stringstream> ss(new stringstream());
shared_stream out(ss);
out << "test";
To release ownership while avoiding calling the deleter.
auto ptr = stream.auto_rdbuf(); /* client takes ownership. */
auto raw_ptr = ptr.get(); /* take raw buffer pointer. */
ptr.release(); /* call release of the managed buffer. */