Singleton Class in C++

前端 未结 3 1629
南方客
南方客 2020-12-17 05:59

I have used singleton calss following the example:

singleton class

But i get the error as \"Unresolved external symbols\"

this is th

3条回答
  •  不知归路
    2020-12-17 06:55

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

提交回复
热议问题