gpt4 book ai didi

c++ - 何时用单例替换全局 std::unique_ptr

转载 作者:可可西里 更新时间:2023-11-01 15:38:31 24 4
gpt4 key购买 nike

一位同事坚持对所有全局指针变量使用 Meyer 的 Singleton,因为“不能保证全局 unique_ptr 的构造不会抛出”。所以不是:

#include <memory>

std::unique_ptr<Foo> ptr(nullptr); // Apparently this isn't safe.

int main(/*blah*/)
{
ptr.reset(new Foo());
}

我们现在有

unique_ptr<Foo> singleton
{
try
{
static unique_ptr<Foo> ptr();
return ptr;
}
catch (...)
{
std::cerr << "Failed to create single instance\n";
exit(1);
}
return unique_ptr<Type>();
}

int main()
{
}

对我来说,这似乎是一种寻找问题的解决方案。他有道理吗?

最佳答案

您的同事不正确(或者可能只是过时了,unique_ptr 的预标准版本可能不同)。 unique_ptrnullptr_t 构造函数保证不抛出 (20.7.1.2):

constexpr unique_ptr (nullptr_t) noexcept : unique_ptr() {}

由于它也是constexpr(而且由于nullptr是一个常量表达式),因此需要在常量初始化时进行初始化(3.6.2/2)。因此,控制初始化顺序(Meyers 单例可能有用的另一个原因)在这里也不适用。

关于c++ - 何时用单例替换全局 std::unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16088650/

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