Search code examples
c++c++11shared-ptr

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?


Solution

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