Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does getInstance() work?

Tags:

c++

oop

static

Recent I read some C++ code using extensively following getInstance() method:

class S
{
    private:
        int some_int = 0;
    public:
        static S& getInstance()
        {
            static S instance; / (*) /
            return instance;
        }
};

From how this code fragment being used, I learned the getInstance() works like return this, returning the address(or ref) of the instance of class S. But I got confused.

1) where does the static variable S defined in line(*) allocated in memory? And why it can work like return this?

2) what if there exist more than one instance of class S, whose reference will be returned?

like image 821
qweruiop Avatar asked Sep 25 '13 05:09

qweruiop


People also ask

What does getInstance method do?

The getInstance() is the method of Java Currency class which is used to get an instance of currency for the given currency code.

Why do we use getInstance () method in Java?

The getInstance() method of java. security. Provider class is used to return a Signature object that implements the specified signature algorithm. This method traverses the list of registered security Providers, starting with the most preferred Provider.

What is true about class getInstance () in Java?

4. What is true about Class. getInstance()? Explanation: Class class provides list of methods for use like getInstance().

Why we use getInstance method in Singleton?

Here, ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.


1 Answers

This is the so-called Singleton design pattern. Its distinguishing feature is that there can only ever be exactly one instance of that class and the pattern ensures that. The class has a private constructor and a statically-created instance that is returned with the getInstance method. You cannot create an instance from the outside and thus get the object only through said method.

Since instance is static in the getInstance method it will retain its value between multiple invocations. It is allocated and constructed somewhen before it's first used. E.g. in this answer it seems like GCC initializes the static variable at the time the function is first used. This answer has some excerpts from the C++ standard related to that.

like image 106
Joey Avatar answered Oct 19 '22 18:10

Joey