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

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


this obviously shouldn't be done:

std::shared_ptr<std::ostream> p_cout(&std::cout);

Indeed, this should never be done. The reason is because you don't have ownership of std::cout and thus when your last shared_ptr goes out of scope it tries to delete std::cout (which is plain evil). But you already knew that.

The solution, if you must absolutely use a shared_ptr (which I assume is a matter of API compatibility), is to use a custom deleter that does nothing:

shared_ptr<std::ostream> p_cout(&std::cout, [](std::ostream*){});