0

I want to test a simple singleton case, write a class C below:

class C {
    static C * ptr_c;
    C(){}
public:
    static C* getInstance()
    {
        if (ptr_c == nullptr)
            ptr_c = new C();
        return ptr_c;
    }
    void show()
    {
        std::cout << "this is class C" << std::endl;
    }
};

with test code:

int main()
{

    C* ptrc = C::getInstance();
    ptrc->show();
}

but it ouput link error:

Undefined symbols for architecture arm64: "C::ptr_c", referenced from: C::getInstance() in test-1db68d.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
  • Which compiler are you using? – kiner_shah Dec 11 '21 at 10:03
  • 3
    you haven't defined `ptr_c`, you've only declared it. Its simpler and safer to move `ptr_c` inside `getInstance`: https://godbolt.org/z/M1Tz5c7bM – Alan Birtles Dec 11 '21 at 10:03
  • 1
    You have to add `C* C::ptr_c` somewhere in your code to define this variable. Currently you only have declared it. – Klaus Dec 11 '21 at 10:05
  • thanks, I need to define the static ptr_c outside the class – FLYFLY Dec 11 '21 at 10:11
  • Don't use new in your singletons, nothing is going to clean them up. Use meyer's singleton instead : https://stackoverflow.com/questions/17712001/how-is-meyers-implementation-of-a-singleton-actually-a-singleton. These singletons will have their destructors called at shutdown, think RAII. – Pepijn Kramer Dec 11 '21 at 10:17

0 Answers0