0

I'm learning about Singleton design pattern. I have the following code example:

//singleton.hpp
#ifndef SINGLETON_HPP
#define SINGLETON_HPP

class Singleton {
public:
    static Singleton& Instance();
private:
    Singleton();
    static Singleton* instance_;
};

#endif

and:

//singleton.cpp
#include "singleton.hpp"

Singleton* Singleton::instance_ = 0;

Singleton& Singleton::Instance() {
    if (instance_ == 0) {
        instance_ = new Singleton();
    }
    return *instance_;
}

Singleton::Singleton() {

}

What I don't understand is the line:

Singleton* Singleton::instance_ = 0;

What does this line do and how? I have never seen something like this.

4

2 回答 2

0

那是一样的

Singleton* Singleton::instance_ = NULL;

它只是在开始时将实例设置为 null,这样当您第一次抓取 Singleton 时,它将新建 Singleton 对象。

然后从那里开始,无论何时您尝试获取 Singleton,它都会为您提供第一个实例化对象。

于 2013-05-10T21:09:58.447 回答
0
Singleton* Singleton::instance_ = 0; 

只是意味着

Singleton* Singleton::instance_ = NULL; 

因为是静态变量,所以需要在.h文件中声明,在.cpp文件中定义

于 2013-05-10T21:10:48.153 回答