为什么在C 中创建单例类创建期间静态函数参考静态变量
why cannot static function reference static variable during singleton class creation in c++?
我试图理解单身设计模式并创建了最简单的模式:
#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也是静态变量?我在这里错过了什么吗?
我在这里错过了什么吗?
是的,有几件事:
- 如前所述,您缺少静态
mySingleton
指针变量的定义。 -
您的代码不是线程安全
实现它的正确方法是在getInstance()
函数(aka。ScottMeyer's Singleton)中使用本地静态变量:static mySingleton* getInstance(){ static mySingleton theInstance; return &theinstance; }
保证此实现是线程安全的,您无需打扰内存分配。
-
使用指针可能不是您想要的返回类型
static mySingleton& getInstance(){ // ^ static mySingleton theInstance; return theinstance; }
static mySingleton *ptr;
类定义内部只是一个声明。这不是一个定义。您需要使用以下方式定义它:
mySingleton * mySingleton::ptr = nullptr;
班级定义以外。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 如何创建对象函数指针C++映射?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 检查编译时是否存在静态函数
- 如何为 v8::P ersistent<v8::Function> 创建到 c++ 函数的包装器
- 如何创建指向函数指针的指针?
- 如何使用类型级函数动态创建静态类型?
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- C - 函数能够访问类方法,而不会创建静态或对象
- 为什么在C 中创建单例类创建期间静态函数参考静态变量
- C++/V8调用非静态函数/创建临时实例的方便方法
- 一个定义规则是否强制创建一个静态函数变量
- 访问在相应类的静态函数中创建的对象的私有成员变量不会导致错误.为什么?
- 如何在test.h中创建模板函数,请在test.cpp中使用静态方法
- 我的非成员静态函数允许更改和创建非静态变量
- 创建一个自由的静态函数有什么优点吗?
- C++ - 为什么不能用"const"限定符创建静态成员函数
- 为非静态成员函数创建unary_function函数