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.
A std::shared_ptr consists of a control block and its resource. The control block is thread-safe, but access to the resource is not. This means modifying the reference counter is an atomic operation and you have the guarantee that the resource is deleted exactly once.
No, std::string is smart enough by itself.
C++11 has introduced three types of smart pointers, all of them defined in the <memory> header from the Standard Library: std::unique_ptr — a smart pointer that owns a dynamically allocated resource; std::shared_ptr — a smart pointer that owns a shared dynamically allocated resource.
4) The copy constructor is deleted; threads are not copyable. No two std::thread objects may represent the same thread of execution.
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 explicitly join
ed or detached
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With