A colleague has insisted on using Meyer's Singleton for all global pointer variables as "there's no guarantee the construction of the global unique_ptr
won't throw". So instead of:
#include <memory>
std::unique_ptr<Foo> ptr(nullptr); // Apparently this isn't safe.
int main(/*blah*/)
{
ptr.reset(new Foo());
}
We now have
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()
{
}
To me this seems like a solution looking for a problem. Does he have a point?
Your colleague is incorrect (or perhaps just out of date, pre-standard versions of unique_ptr
might be different). The nullptr_t
constructor of unique_ptr
is guaranteed not to throw (20.7.1.2):
constexpr unique_ptr (nullptr_t) noexcept : unique_ptr() {}
Since it's also constexpr
(and since nullptr
is a constant expression), it is required to be initialized during constant initialization (3.6.2/2). So controlling initialization order (the other reason the Meyers singleton might be useful) also doesn't apply here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With