getInstance()如何工作? [英] How does getInstance() work?
问题描述
最近我使用广泛的getInstance()方法读取了一些C ++代码:
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;
}
};
从这个代码片段的使用方式,我学习了getInstance > return this ,返回类S
的实例的地址(或引用)。但是我感到困惑。
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)在内存中分配的行(*)中定义的静态变量 S
?为什么它可以工作返回这个
?
1) where does the static variable S
defined in line(*) allocated in memory? And why it can work like return this
?
2)如果存在多个<$
2) what if there exist more than one instance of class S
, whose reference will be returned?
推荐答案
这是所谓的称为 getInstance
方法一起返回。
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.
由于实例
是
这篇关于getInstance()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!