C ++中的Shared_ptr和内存可见性 [英] Shared_ptr and Memory Visibility in c++

查看:125
本文介绍了C ++中的Shared_ptr和内存可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在线程A上用shared_ptr堆分配一个对象,则将shared_ptr复制到另一个线程,而无需进行任何同步.是否可以保证另一个线程看到一个完全构造的对象?

If you heap allocate an object with shared_ptr on thread A , then copy the shared_ptr to another thread without any synchronization. Is the other thread guaranteed to see a fully constructed object?

int main(){
    auto sp = std::make_shared<int>(5);
    auto f=std::async(std::launch::async, [sp](){
    std::cout<<*sp;});
}

可以保证打印5张吗?

推荐答案

在您的示例中,shared_ptr对象在 std::async返回之前已被复制,因此它仍存在于新线程中即使原始的shared_ptr在第二个线程访问它的副本之前已被销毁.

In your example, the shared_ptr object has been duplicated before std::async returns, hence it still exists in the new thread even if the original shared_ptr is destroyed before the second thread accesses it's copy.

因此,答案是肯定的.您正在按值传递,因此是副本.

So, the answer is yes. You are passing by value, hence a copy.

这篇关于C ++中的Shared_ptr和内存可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆