为什么在C 中创建单例类创建期间静态函数参考静态变量

why cannot static function reference static variable during singleton class creation in c++?

本文关键字:创建 静态函数 参考 静态 变量 单例类 为什么      更新时间:2023-10-16

我试图理解单身设计模式并创建了最简单的模式:

#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也是静态变量?我在这里错过了什么吗?

我在这里错过了什么吗?

是的,有几件事:

  1. 如前所述,您缺少静态mySingleton指针变量的定义。
  2. 您的代码不是线程安全
    实现它的正确方法是在getInstance()函数(aka。ScottMeyer's Singleton)中使用本地静态变量:

    static mySingleton* getInstance(){
        static mySingleton theInstance;
        return &theinstance;
    }
    

    保证此实现是线程安全的,您无需打扰内存分配。

  3. 使用指针可能不是您想要的返回类型

    static mySingleton& getInstance(){
                   // ^
        static mySingleton theInstance;
        return theinstance;
    }
    
static mySingleton *ptr;

类定义内部只是一个声明。这不是一个定义。您需要使用以下方式定义它:

mySingleton * mySingleton::ptr = nullptr;

班级定义以外。