我试图理解单身设计模式并创建了一个最简单的模式:
#include <iostream>
class mySingleton{
private:
static mySingleton *ptr;
mySingleton(){ }
public:
static mySingleton* getInstance(){
if(!ptr){
ptr = new mySingleton();
return ptr;
} else return ptr;
}
void msg(){
std::cout << " Hello World!! " << std::endl;
}
};
int main(){
mySingleton* obj = mySingleton::getInstance();
mySingleton* obj2 = mySingleton::getInstance();
return 0;
}
当我尝试编译时,我得到:
Undefined symbols for architecture x86_64:
"mySingleton::ptr", referenced from:
mySingleton::getInstance() in ccm822LI.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
为什么我不能在静态函数中使用ptr,因为ptr也是一个静态变量?我在这里错过了什么吗?
答案 0 :(得分:7)
我在这里错过了什么吗?
是的,有几件事:
mySingleton
指针变量的定义。您的代码不是线程安全的
实现它的正确方法是在getInstance()
函数(aka。Scott Meyer's Singleton)中使用局部静态变量:
static mySingleton* getInstance(){
static mySingleton theInstance;
return &theinstance;
}
这个实现保证是线程安全的,你不需要为内存分配而烦恼。
使用指针可能不是您想要的返回类型
static mySingleton& getInstance(){
// ^
static mySingleton theInstance;
return theinstance;
}
答案 1 :(得分:3)
static mySingleton *ptr;
在类定义中只是一个声明。这不是一个定义。您需要使用以下方法定义它:
mySingleton * mySingleton::ptr = nullptr;
在课程定义之外。