Lazy Initialization

suggest change

This example has been lifted from the Q & A section here:

See this article for a simple design for a lazy evaluated with guaranteed destruction singleton:

The classic lazy evaluated and correctly destroyed singleton.

class S
        static S& getInstance()
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        S() {};                   // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Dont forget to declare these two. You want to make sure they
        // are unacceptable otherwise you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status

See this article about when to use a singleton: (not often)

See this two article about initialization order and how to cope:

See this article describing lifetimes:

See this article that discusses some threading implications to singletons:

See this article that explains why double checked locking will not work on C++:

Feedback about page:

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

Table Of Contents