Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
        }
};
like image 517
cacau Avatar asked Jan 21 '14 07:01

cacau


People also ask

Does Singleton allow lazy initialization?

Singleton Class in Java using Lazy LoadingThe instance could be initialized only when the Singleton Class is used for the first time. Doing so creates the instance of the Singleton class in the JVM Java Virtual Machine during the execution of the method, which gives access to the instance, for the first time.

What is lazy and early loading of Singleton and how will you implement it?

What is lazy and early loading of Singleton and how will you implement it in java? Both these refer to when the Singleton object gets created in the application. In lazy loading it is created only when the method creating the instance is first called. In early loading the instance is created once the class is loaded.

What is the difference between early instantiation and lazy instantiation in a singleton class?

Lazy initialization is technique were we restrict the object creation until its created by application code. This saves the memory from redundant objects which some time may be very big/heavy. In other way eager initialization creates the object in advance and just after starting the application or module.

What is the main advantage of lazy loading instead eager loading for a singleton?

In situations like on-demand object creation where we create an object of the class only when it is accessed, lazy initialization works very well. It helps application load faster because it does not depend upon instance creation at the time of application startup.


2 Answers

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.
like image 54
stefaanv Avatar answered Sep 26 '22 01:09

stefaanv


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

Thus yes, it facilitates lazy initialization.

like image 27
πάντα ῥεῖ Avatar answered Sep 25 '22 01:09

πάντα ῥεῖ