Static deinitialization-safe singleton.

suggest change

There are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all the static objects that use the singleton no longer need it.

In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:

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;
    }

private:
    Singleton() {}
};

NOTE: This example appears as an answer in the Q&A section here.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents