问题
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:
- As mentioned you are missing the definition of the static
mySingleton
pointer variable. Your code isn't thread safe
The correct way to implement it is to use a local static variable in thegetInstance()
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.
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