Storing an std::thread in C++11 smart pointer

拥有回忆 提交于 2020-07-05 07:57:13

问题


In C++ 11 & above what are the advantages or disadvantages when storing an std::thread as a member of class directly like so:

std::thread my_thread;

As opposed to storing a std::shared_ptr or std::unique_ptr to the thread like so:

std::shared_ptr<std::thread> my_thread_ptr;

Is any of the code options better than other? Or it doesn't matter, just 2 separate ways of handling the thread object.


回答1:


May be there is some less common reason for usage of pointer (or smart pointer) member but for common usages it seems that std::thread either does not apply or is sufficiently flexible itself:

  • We may want more control over lifetime of object, for example to initialize it "lazily". The std::thread already supports it. It can be made in "not representing a thread" state, assigned real thread later when needed, and it has to be explicitly joined or detacheded before destruction.
  • We may want a member to be transferred to/from some other ownership. No need of pointer for that since std::thread already supports move and swap.
  • We may want the object pointed at to be dynamically polymorphic. That does not apply since std::thread does not have any virtual member functions.
  • We may want opaque pointer for to hide implementation details and reduce dependencies, but std::thread is standard library class so we can't make it opaque.
  • We may want to have shared ownership. That is fragile scenario with std::thread. Multiple owners who can assign, swap, detach or join it (and there are no much other operations with thread) can cause complications.
  • There is mandatory cleanup before destruction like if (xthread.joinable()) xthread.join(); or xthread.detach();. That is also more robust and easier to read in destructor of owning class instead of code that instruments same thing into deleter of a smart pointer.

So unless there is some uncommon reason we should use thread as data member directly.




回答2:


If you have an option of having your std::thread as a member variable, go for it. If not, consider other options. Don't wrap it inside std::shared_ptr or std::unique_ptr unless you have a serious reason for doing so. Given that std::thread is movable by itself, it's pretty unlikely wrapping it into a smart pointer will be necessary.



来源:https://stackoverflow.com/questions/44832054/storing-an-stdthread-in-c11-smart-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!