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:


Singleton:
* Static deinitialization-safe singleton.

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
78 Singleton
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype