简体   繁体   中英

Static private data member in Singleton class

Singleton design pattern says that we should define a private static attribute in the "single instance" class. 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?

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

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. If "instance" is not static, not part of "the class", then "getInstance" cannot return the instance.

Try to run the following code with instance declared as non static:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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