Search code examples
c++c++11c++14shared-ptrstdthread

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


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.


Solution

  • 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.