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.
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: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 explicitlyjoin
ed ordetached
ed before destruction.std::thread
already supports move and swap.std::thread
does not have any virtual member functions.std::thread
is standard library class so we can't make it opaque.std::thread
. Multiple owners who can assign, swap, detach or join it (and there are no much other operations with thread) can cause complications.if (xthread.joinable()) xthread.join();
orxthread.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.
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
orstd::unique_ptr
unless you have a serious reason for doing so. Given thatstd::thread
is movable by itself, it's pretty unlikely wrapping it into a smart pointer will be necessary.