Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to replace a global std::unique_ptr with a singleton

Tags:

c++

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?

like image 249
James Avatar asked Apr 18 '13 16:04

James


Video Answer


1 Answers

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.

like image 159
Steve Jessop Avatar answered Oct 07 '22 01:10

Steve Jessop