cacau
cacau

Reputation: 3646

Lazy initialization with singleton pattern

Would the following code facilitate lazy initialization?
Or would the singletonInstance be created as soon as somebody includes the header (or even at program startup time)?

class SingletonClass
{
    private:
         SingletonClass();
        ~SingletonClass();

    public: 

        static const SingletonClass& Instance()
        {
            static SingletonClass singletonInstance;
            return singletonInstance; 
        }
};

Upvotes: 15

Views: 11497

Answers (2)

stefaanv
stefaanv

Reputation: 14392

This is known as the Meyers singleton and they are lazy instantiated.

There are some considerations:

  • the singletons will be destroyed at the end of the program in the reverse order in which they are created, so there can be dependency issues.
  • C++03 doesn't guarantee against race conditions in multithreaded environments.

Upvotes: 17

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

The SingletonClass constructor will not be called earlier than somenone calls the Instance() method.

Thus yes, it facilitates lazy initialization.

Upvotes: 10

Related Questions