【发布时间】:2016-03-30 14:01:55
【问题描述】:
目前我正在使用这种方法:
class Singleton {
public:
static Singleton &getInstance() {
static Singleton *instance = new Singleton();
return *instance;
}
void getData();
private:
Singleton() {}
};
这样我就可以使用Singleton写作中的一个方法了:
Singleton::getInstance.getData();
这似乎是阅读大量 C++11 教程的正确方式。 但是通过 cocos Director 单例代码(还有 FileUtils 等),我看到 Cocos 使用了另一种方法:
class Singleton {
public:
static Singleton *getInstance() {
instance = new Singleton();
return instance;
}
void getData();
private:
Singleton() {}
static Singleton *instance;
};
用这种方法我必须写:
Singleton::getInstance->getData();
因为指针*getInstance而不是引用&getInstance。
我觉得差别很大,但不知道是不是一种方式正确,另一种方式不正确。
请帮我理清这个概念。
【问题讨论】:
-
c++ 中不需要单例。使用返回对静态对象的引用的函数。
-
谢谢@RichardHodges 能给我一些具体的链接吗?我想要一个用于创建共享游戏数据对象的单例,我认为这是正确的方法。
标签: c++ c++11 singleton cocos2d-x