0

I define a static member in a class, but i can't assign static member in static function. ERROR: "Undefined symbols for architecture x86_64: "SingleInstance::sm". This is my c++ code:

#include <iostream>

using namespace std;
class SingleInstance {      
public:
    static void getInstance()
    {

            sm = new SingleInstance();
            cout <<"build new instance" << endl;
    }
private:
            SingleInstance(){}
            ~SingleInstance(){}
            static SingleInstance* sm;

};
int main()
{
       SingleInstance::getInstance();
       return 0;
}
PZY
  • 131
  • 1
  • 16
  • 1
    You need to define it outside the class, `SingleInstance* SingleInstance::sm;`. – songyuanyao Apr 08 '18 at 15:09
  • @songyuanyao Why must define it outside the class. getInstance() and sm have the same scope. – PZY Apr 08 '18 at 15:16
  • 1
    @panzhengyu • the "why" is because defining it causes the compiler to emit the backing storage for the identifier. Without defining it, the compiler is not aware that the backing storage was not provided. Since the backing storage may be in any of the translations units... even if the program is small, and only has one translation unit. – Eljay Apr 08 '18 at 15:33

0 Answers0