* std :: shared_ptr线程的运算符安全吗?

时间:2020-05-18 10:51:53

标签: c++11 operators shared-ptr

我有一个std::shared_ptr,它可以从回调中异步更改。

在主线程中,我想读取“最新”值并对其进行复杂的计算,并且我不关心在运行这些计算时指针的值是否发生变化。

为此,我只是在主线程上复制包含的值:

// async thread
void callback(P new_data) {
  smart_pointer_ = new_data;
}

// main thread loop!
Value copy_of_pointer_value = *smart_pointer_; // smart_pointer_ could be changing in callback right now
// do calcs with copy_of_pointer_value

这样安全吗?还是应该在尝试读取智能指针的值之前显式地对其进行复制,如下所示:

// main thread loop!
auto smart_copy = smart_pointer_;
// I know I could work with *smart_copy directly, but I need to copy anyway for other reasons
Value copy_of_pointer_value = *smart_copy;
// do calcs with copy_of_pointer_value

0 个答案:

没有答案
相关问题