开发者

C++ Singleton Implementation - Problems with static

It has been a while since I've programmed in C++. I was trying to implement a singleton class, but I get an unresolved external symbol. Can you guys point out out to resolve this problem? Thanks in advance!

class Singleton
{
    Singleton(){}
    Singleton(const Singleton & o){}
    static Singleton * theInstance;

public:
    static Singleton getInstance()
    {
        if(!theInstance)
            Singleton::theInstance = new Singleton();

        return * theInstance;
    }
};

Errors:

Error 3 error LNK1120: 1 unresolved externals

Error 2 error LNK2001: unresolved external symbol "private: static class Singleton * Singleton::theInstance" (?theInstance@Singleto开发者_运维问答n@@0PAV1@A)


You have declared Singleton::theInstance, but you have not defined it. Add its definition in some .cpp file:

Singleton* Singleton::theInstance;

(Also, Singleton::getInstance should return a Singleton& rather than a Singleton.)


You need to provide a definition of theInstance outside the class declaration, in a C++ implementation file:

Singleton *Singleton::theInstance;


Alternatively to all the other answers, you could just do away with the private member and use a static-scope function variable:

static Singleton getInstance()
{
   static Singleton * theInstance = new Singleton(); // only initialized once!
   return *theInstance;
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜