I'm having trouble storing std::cout
in a std::shared_ptr<std::ostream>
.
Since this obviously shouldn't be done:
std::shared_ptr<std::ostream> p_cout(&std::cout);
And this isn't even possible since it's not possible to copy a std::ostream:
std::shared_ptr<std::ostream> p_cout = std::make_shared<std::ostream>(std::cout);
Does someone know a legal workaround?
The std::ostream , the std::istream or the std::iostream are base classes of stream types (e.g. std::stringstream , std::fstream , etc.) in the Standard Library.
ostream is a general purpose output stream. cout and cerr are both examples of ostreams. ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file.
The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr . Constructing a new shared_ptr using the raw underlying pointer owned by another shared_ptr leads to undefined behavior.
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
The requirement you have is strange, but you can of course store a pointer to std::ostream
in a shared_ptr<std::ostream>
provided, you take care of a proper disposer action:, e.g.: std::shared_ptr<std::ostream>(&std::cout, [](void*) {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With