Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 std::shared_ptr<std::ostream> from std::cout

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?

like image 353
Tim Avatar asked Jun 20 '13 17:06

Tim


People also ask

What is std :: ostream?

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.

Is Ostream a cout?

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.

Can you copy a shared_ptr?

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.

What is C++ shared_ptr?

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.


1 Answers

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*) {});

like image 93
Paul Michalik Avatar answered Oct 30 '22 12:10

Paul Michalik