0
using namespace std;
class singleton_l  //lazy
{  
    private:  
        singleton_l(){cout << "lazy singleton created" << endl;}    
        ~singleton_l(){}
        static singleton_l* Instance;  
    public:  
        static singleton_l* GetInstance()  
        {  
            if (Instance == nullptr)
                Instance = new singleton_l();  
            return Instance;  
        }  
        void show()
        {
            cout << "I'm a instance of singleton_l" << endl;
        }
}; 


int main() {

    singleton_l * s1; 
    s1->GetInstance();  //use singleton::GetInstance() will have the same compile error
    s1->show();

    return 0;
}

when I compile it with 'g++ test_singleton.cpp', the output error is below:

Undefined symbols for architecture arm64: "singleton_l::Instance", referenced from: singleton_l::GetInstance() in test_singleton-00665a.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

FLYFLY
  • 49
  • 6
  • *is there something wrong with my c++ singleton design pattern code?* -- Even if you got this code to build without error, it is not thread-safe. – PaulMcKenzie Nov 08 '21 at 15:40
  • yes, that‘s the reason, I have solved it, thanks very much! – FLYFLY Nov 08 '21 at 15:54
  • As noted, your implementation is not thread safe. If multiple threads were to hit the `GetInstance`, there is a chance that the singleton will be initialized twice (or maybe even more than twice). Instead of this, see the [Meyers singleton](https://stackoverflow.com/questions/17712001/how-is-meyers-implementation-of-a-singleton-actually-a-singleton) – PaulMcKenzie Nov 08 '21 at 15:57
  • Handy reading: [Answer 1 of C++ Singleton design pattern](https://stackoverflow.com/a/1008289/4581301) outlines a generally better approach to singletons. – user4581301 Nov 08 '21 at 15:57

0 Answers0