在C ++ 11智能指针中存储std :: thread [英] Storing an std::thread in C++11 smart pointer
问题描述
在 C ++ 11
中&上面优点或缺点是什么,当直接将 std :: thread
作为类的成员存储时,就像这样:
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;
与存储 std :: shared_ptr
或 std :: unique_ptr
这样的线程:
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.
推荐答案
可能是一些不太常见的原因对于指针(或智能指针)成员的使用,但对于常见用法, std :: thread
似乎不适用或本身不够灵活:
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
已经支持它。可以使其处于不代表线程状态,需要时在以后分配实际线程,并且必须显式join
ed或detached
,然后销毁。 - 我们可能希望成员与其他所有权转移。不需要指针,因为
std :: thread
已经支持移动和交换。 - 我们可能希望指向的对象是动态多态的。这不适用,因为
std :: thread
没有任何虚拟成员函数。 - 我们可能希望使用不透明的指针来隐藏实现详细信息并减少依赖关系,但是
std :: thread
是标准库类,因此我们不能使其变得不透明。 - 我们可能希望拥有所有权。使用
std :: thread
的情况很脆弱。可以分配,交换,分离或加入它的多个所有者(线程没有太多其他操作)可能会导致并发症。 - 在销毁之前必须进行强制清理,例如
if(xthread.joinable())xthread.join();
或xthread.detach();
。在拥有类的析构函数中,而不是在智能指针的删除器中插入相同内容的代码中,这也更加健壮,更易于阅读。
- 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 explicitlyjoin
ed ordetached
ed 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();
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.
这篇关于在C ++ 11智能指针中存储std :: thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!