STD :: MOVE of shared_ptr线程安全吗?
以下片段运行良好:
#include <memory>
#include <cassert>
int main()
{
auto ptr1 = std::make_shared<int>(10);
assert(ptr1.use_count() == 1);
auto ptr2 = std::move(ptr1);
assert(ptr1 == nullptr);
auto ptr3 = static_cast<std::shared_ptr<int>&&>(ptr2);
assert(ptr2 == nullptr);
assert(ptr3.use_count() == 1);
}
看起来std ::移动
是否有几个操作,其中一个正在以某种方式重置移动的共享指针,那么此线程安全吗?例如,如果我有类似的东西:
void ThreadLogic()
{
if (sharedPtr != nullptr)
{
DoSomething(std::move(sharedPtr));
}
else
{
DoSomethingElse();
}
}
std :: move(sharedptr)
aromic还是应该通过其他一些方式保护该支票(关键部分)?
The following snippet runs fine:
#include <memory>
#include <cassert>
int main()
{
auto ptr1 = std::make_shared<int>(10);
assert(ptr1.use_count() == 1);
auto ptr2 = std::move(ptr1);
assert(ptr1 == nullptr);
auto ptr3 = static_cast<std::shared_ptr<int>&&>(ptr2);
assert(ptr2 == nullptr);
assert(ptr3.use_count() == 1);
}
It looks std::move
does several operations, one of them is reseting the moved shared pointer somehow, so is this thread safe? For instance if i have something like:
void ThreadLogic()
{
if (sharedPtr != nullptr)
{
DoSomething(std::move(sharedPtr));
}
else
{
DoSomethingElse();
}
}
Is that std::move(sharedPtr)
atomic or should I protect the check (the critical section) there by some other means?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您对什么
std :: Move
有误解。实际上,std ::移动
什么都不做。这只是具有含义的编译时间机制:我不再需要此名称的值。然后,这会导致编译器以不同的方式使用该值,例如调用移动构造函数/分配代替复制构造函数/分配。但是
std ::移动
本身不会生成无代码,因此没有任何影响。您应该问的真正的问题是,
shared_ptr
的移动构造函数是否安全,答案是:否。代码> shared_ptr ,但也要分享它的指标。请勿通过引用线程传递
shared_ptr
,而是按值传递,以便每个线程获得其sharone_ptr
。然后,可以随意移动而毫无问题。shared_ptr
保护指出的事物的寿命。参考计数shared_ptr
使用是线程安全的,但别无其他。它只以线程安全的方式管理对象的寿命,因此只要任何shared_ptr
都持有对象,就不会被破坏。You have a misconception about what
std::move
does. In factstd::move
does nothing. It's just a compile time mechanism with the meaning: I no longer need this named value.This then causes the compiler to use the value in different ways, like call a move constructor/assignment instead of copy constructor/assignment. But the
std::move
itself generates no code so nothing to be affected by threads.The real question you should be asking is whether the move constructor of
shared_ptr
is thread safe and the answer is: No.But the point of the
shared_ptr
is not to share theshared_ptr
but to share what it points too. Do not pass ashared_ptr
by reference to threads, instead pass it by value so each thread gets it ownshared_ptr
. Then it is free to move that around at will without problems.The
shared_ptr
protects the lifetime of the thing it points to. The reference count theshared_ptr
uses is thread safe but nothing else. It only manages the lifetime of the pointed to objects in a thread safe way so it doesn't get destroyed as long as anyshared_ptr
has hold of the object.