简体   繁体   English

Singleton类中的静态私有数据成员

[英]Static private data member in Singleton class

Singleton design pattern says that we should define a private static attribute in the "single instance" class. Singleton设计模式说,我们应该在“单个实例”类中定义一个私有静态属性。 However there was no proper explanation why the data member has to be private static. 但是,没有适当的解释为什么数据成员必须是私有静态的。 Will it make any difference if the data member is just private? 如果数据成员只是私有的,会有所不同吗?

In the following code: 在下面的代码中:

class Singleton
{
public:
    static Singleton* getInstance();

private:
    Singleton(){/*Private constructor*/}
    ~Singleton(){/*Private destructor*/}
    static Singleton * instance; //Why static is required?
};

Will it make any difference if the data member instance is not static? 如果数据成员instance不是静态的,会有所不同吗?

EDIT: By putting the destructor in public, will it change the property of singleton design? 编辑:通过将析构函数公开,它会改变单例设计的属性吗?

For a class to be singleton you should forbid users from creating object from it. 要使类成为单例,您应禁止用户从中创建对象。 So you have the constructor private and prevent the copy constructors and assignment operators also. 因此,您可以将构造函数设为私有,并防止复制构造函数和赋值运算符。

Classname(Classname const&) = delete;
Classname(Classname const&&) = delete;
Classname& operator=(classname const&) = delete;
Classname& operator=(classname const&&) = delete;

Then the only way to get an instance to it is using some static function of the class and static functions can access only static variables. 然后,获取实例的唯一方法是使用类的某些静态函数,并且静态函数只能访问静态变量。 Thats why the instance variable is always static variable. 这就是为什么实例变量始终是静态变量的原因。

Another alternative for the getInstance is getInstance的另一种选择是

static Classname& getInstance()
{
    static Classname instance;
    return instance;
}

Static means it is part of the class and all the objects (instances) for that class will point to the same instance. 静态意味着它是类的一部分,并且该类的所有对象(实例)将指向同一实例。

"getInstance" is a static method which can only access static objects. “ getInstance”是一个静态方法,只能访问静态对象。 If "instance" is not static, not part of "the class", then "getInstance" cannot return the instance. 如果“实例”不是静态的,不是“类”的一部分,则“ getInstance”不能返回该实例。

Try to run the following code with instance declared as non static: 尝试使用声明为非静态的实例运行以下代码:

static Singleton* getInstance()
{ 
    if (instance == nullptr) 
        instance = new Singleton();
    return instance;
}

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

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