gpt4 book ai didi

c++ - 通过 shared_ptr 返回的 Singleton 对象是线程安全的吗?

转载 作者:太空狗 更新时间:2023-10-29 21:31:47 27 4
gpt4 key购买 nike

我正在阅读问题的答案。 C++ Singleton design pattern

answer 之一建议使用 shared_ptr 来保证多个静态对象访问单例对象时的生命周期。我注意到这里的 shared_ptr 是使用 new 构造的,并且是按值返回的。

使用 new 来构建 shared_ptr 是原子的还是线程安全的?

我的第二个困惑是关于 RVO。我尝试在我的实现中创建两个单例对象。

shared_ptr 显示了三个 _Uses 和一个 _Weak。我预计 _Uses 计数为 2。在 Visual Studio 15.5.6 上进行了全面优化。RVO 在这里不起作用吗?

class Singleton
{
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;

static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}

~Singleton() {}
private:
Singleton() {}
};

int main()
{
std::shared_ptr<Singleton> obj1 = Singleton::instance();
std::shared_ptr<Singleton> obj2 = Singleton::instance();
return 0;
}

最佳答案

Is using new for shared_ptr construction atomic/thread_safe?

是的,shared_ptr 的创建是线程安全的,因为 static 初始化是线程安全的(另见 this question)

The shared_ptr shows three _Uses and one _Weak. I expected _Uses count to be two. Optimization is full on Visual Studio 15.5.6. Is RVO not functioning here?

您的使用次数为 3,因为 shared_ptr 被声明为 static,这意味着当它被初始化时,对象被创建,因此使用次数增加一个(主要的两个 shared_ptr +2)。当 static shared_ptr 被销毁时,此使用计数只会再次减少,并且这会在程序终止时发生。

关于c++ - 通过 shared_ptr 返回的 Singleton 对象是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57232761/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com