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?
The getInstance() is the method of Java Currency class which is used to get an instance of currency for the given currency code.
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.
4. What is true about Class. getInstance()? Explanation: Class class provides list of methods for use like getInstance().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With