Lazy Initialization

suggest change

This example has been lifted from the Q & A section here:http://stackoverflow.com/a/1008289/3807729

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

http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c/271104#271104

The classic lazy evaluated and correctly destroyed singleton.

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        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.
    public:
        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)

http://stackoverflow.com/questions/86582/singleton-how-should-it-be-used

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

http://stackoverflow.com/questions/211237/c-static-variables-initialisation-order/211307#211307

http://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746

See this article describing lifetimes:

http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function

See this article that discusses some threading implications to singletons:

http://stackoverflow.com/questions/449436/singleton-instance-declared-as-static-variable-of-getinstance-method/449823#449823

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

http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about/367690#367690

Feedback about page:

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



Table Of Contents