Tim
Tim

Reputation: 5691

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?

Upvotes: 11

Views: 5277

Answers (3)

Paul Michalik
Paul Michalik

Reputation: 4381

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

Upvotes: 17

syam
syam

Reputation: 15089

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

Upvotes: 14

Fran&#231;ois Moisan
Fran&#231;ois Moisan

Reputation: 790

shared_ptr will take ownership of the pointer you give it. This means your program will eventually try to delete std::cout (when that last copy of a the initial shared_ptr goes out of scope). This is not something you want to do.

Since you do not need to control the lifetime to std::cout, you could simply pass a std::ostream raw pointer or reference around.

Upvotes: -1

Related Questions