简体   繁体   中英

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?

您的要求很奇怪,但是您当然可以将指向std::ostream的指针存储在提供的shared_ptr<std::ostream> ,您可以处理适当的处置器操作:,例如: 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*){});

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.

Try this:

auto p_cout = std::make_shared<std::ostream>(std::cout.rdbuf());

:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM