开发者

Boost C++ Singleton error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" (?flag@HL@Nsp@@0JA)

开发者 https://www.devze.com 2022-12-25 00:11 出处:网络
I try to create a multi-threaded singleton pattern class. Header: class HL{ public: static HL* getInstance();

I try to create a multi-threaded singleton pattern class.

Header:

class HL{

    public:
        static HL* getInstance();
    .........
    private:
        static开发者_C百科 HL* instance;
        static boost::once_flag flag;
        HL();
        static void initOnce();
}

CPP:

HL* HL::instance = NULL;

HL* HL::getInstance(){
    if(instance == NULL){
        boost::call_once(flag, initOnce);
    }
    return instance;
}

void HL::initOnce(){
    instance = new HL();
}

I get this error:

error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" (?flag@HL@Nsp@@0JA)

What's wrong?


You need to define the static member variable in the cpp file:

boost::once_flag Nsp::HL::flag;

You can initialize it if you need to (I've not used boost::once_flag, and can't tell you whether or how it needs to be initialized):

boost::once_flag Nsp::HL::flag = {whatever goes here};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号