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

ε祈祈猫儿з 提交于 2019-12-12 03:38:20

问题


I was trying to understand singleton design pattern and created a simplest one:

#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;
}

When I try to compile I get :

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

Why can't I use ptr inside a static function, since ptr is also a static variable? Am I missing something here?


回答1:


Am I missing something here?

Yes, several things:

  1. As mentioned you are missing the definition of the static mySingleton pointer variable.
  2. Your code isn't thread safe
    The correct way to implement it is to use a local static variable in the getInstance() function (aka. Scott Meyer's Singleton):

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

    This implementation is guaranteed to be thread safe, and you don't need to bother with memory allocation.

  3. Using a pointer probably isn't what you want as a return type

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



回答2:


static mySingleton *ptr;

inside the class definition is just a declaration. It is not a definition. You need to define it using:

mySingleton * mySingleton::ptr = nullptr;

outside the class definition.



来源:https://stackoverflow.com/questions/37998408/why-cannot-static-function-reference-static-variable-during-singleton-class-crea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!