Singleton Class in C++

ⅰ亾dé卋堺 提交于 2019-11-29 05:15:54

For a start, I think:

singleton();

should be:

instance = new singleton();

The way you have it, you're not actually storing the newly instantiated object so instance will always be null.

It's also good form to explicitly set statics with:

singleton *singleton::instance = 0;

(outside the class definition).

In fact, it's possibly better to start with the baseline singleton code and work your way up from there. This is a standard-form pointer version:

#include <iostream>

class singleton {
    protected:
        static singleton *instance;
        singleton() { }
    public:
        static singleton *getInstance() {
            if (instance == 0)
                instance = new singleton();
            return instance;
        }
};
singleton *singleton::instance = 0;

int main() {
    singleton *s1 = singleton::getInstance();
    singleton *s2 = singleton::getInstance();
    std::cout << s1 << '\n';
    std::cout << s2 << '\n';
    return 0;
}

You can see that both pointers are the same from the output:

0xbc0358
0xbc0358

Or the reference version, since that seems to be what you're aiming for:

#include <iostream>

class singleton {
    protected:
        static singleton *instance;
        singleton() { }
    public:
        static singleton& getInstance() {
            if (instance == 0)
                instance = new singleton();
            return *instance;
        }
};
singleton *singleton::instance = 0;

int main() {
    singleton &s1 = singleton::getInstance();
    singleton &s2 = singleton::getInstance();
    std::cout << &s1 << '\n';
    std::cout << &s2 << '\n';
    return 0;
}

In your definition file, you need the definition of instance:

singleton* singleton::instance = NULL;

You should separate your definition from your declaration if you want to use the singleton in multiple translation units.

Also, the way it's usually done, is not having an initialize method:

static singleton* getInstance()
{ 
    if(instance==NULL)
        instance = new singleton();
    return instance;
}

There are lots of discussions on SO whether singletons are good or bad, with the general consensus that they should be avoided. You should also check them out.

You need to define the static member variable instance. Somewhere in global scope (for example between the class and the main function) add the following line:

singleton *singleton::instance = 0;  // use 'nullptr' if your compiler support it

Also, you can put the initialization of the instance in getInstance:

static singleton& getInstance()
{
    if (instance == 0)
        instance = new singleton;
    return *instance;
}

and remove the initialize function.

You might also want to make the constructor private instead of protected, as well as having private copy-constructor and assignment functions to prevent copying and assignment.

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