简体   繁体   English

c++ singleton 每次都创建新实例吗?

[英]does c++ singleton create new instance every time?

C++ singleton code looks like this: C++ singleton 代码如下所示:

MyClass& MyClass::getInstance(){
    static MyClass instance;
    return instance;
}

Looking specifically at static MyClass instance;具体static MyClass instance;

Is a new instance created each time getInstance is called?每次调用 getInstance 时是否都会创建一个新instance

Because the MyClass member variable is declared as static and you are returning a reference to it, not a copy.因为MyClass成员变量被声明为static并且您返回的是对它的引用,而不是副本。 Static member variables are not created per-object like normal member variables; Static 成员变量不像普通成员变量那样按对象创建; rather, there is one instance of the variable accessible from all objects of the class.相反,有一个变量实例可从 class 的所有对象访问。

See here.看这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM