一位同事坚持将Meyer的Singleton用于所有全局指针变量,因为"不能保证全局构建unique_ptr不会抛出".所以代替:
#include <memory>
std::unique_ptr<Foo> ptr(nullptr); // Apparently this isn't safe.
int main(/*blah*/)
{
ptr.reset(new Foo());
}
Run Code Online (Sandbox Code Playgroud)
我们现在有
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()
{
}
Run Code Online (Sandbox Code Playgroud)
对我来说,这似乎是寻找问题的解决方案.他有意见吗?
Ste*_*sop 21
您的同事不正确(或者可能只是过时,预标准版本unique_ptr可能不同).该nullptr_t的构造函数unique_ptr保证不会抛出(20.7.1.2):
constexpr unique_ptr (nullptr_t) noexcept : unique_ptr() {}
Run Code Online (Sandbox Code Playgroud)
因为它也是constexpr(并且因为它nullptr是一个常量表达式),所以需要在常量初始化期间初始化(3.6.2/2).因此,控制初始化顺序(Meyers单例可能有用的另一个原因)也不适用于此处.