0

I am trying to create thread safe singleton class here is my code:

#include<iostream>
#include<mutex>

using namespace std;
std::mutex mtx;

class MySingleton{
private:
    static MySingleton * singletonInstance;
    MySingleton();
    MySingleton(const MySingleton&);
    const MySingleton& operator=(const MySingleton&);
    ~MySingleton();
public:
    static MySingleton* GetInstance();
    void foo();
};

MySingleton::MySingleton(){
    std::cout << "Ctor\n";
};

MySingleton::~MySingleton(){
    std::cout << "Dtor\n";
};

void MySingleton::foo()
{
    cout << "Inside Foo" << endl;
}

MySingleton* MySingleton::GetInstance(){
    //double check
    if (singletonInstance == NULL){
        std::lock_guard<std::mutex> lock(mtx);
        if (singletonInstance == NULL)
            singletonInstance = new MySingleton();
    }
    return singletonInstance;
}

int main(void){
    MySingleton::GetInstance()->foo();
}

I executed this code in VS2015 and found the below error:

1>Source.obj : error LNK2001: unresolved external symbol "private: static class MySingleton * MySingleton::singletonInstance" (?singletonInstance@MySingleton@@0PAV1@A)
1>E:\CPP\Test\Debug\Singleton.exe : fatal error LNK1120: 1 unresolved externals

I am not sure what is missing in my code,just wanted to call the foo() with the singleton instance. Can any one help to figure out the cause of error?

A. Gupta
  • 77
  • 2
  • 9

1 Answers1

2

In C++ you need to initialize static members outside of the class, in a source (.cpp) file, like this:

/** your singleton class definition **/

MySingleton* MySingleton::singletonInstance = nullptr;

/** rest of your code **/
V0ldek
  • 9,623
  • 1
  • 26
  • 57