views:

188

answers:

1

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

Header:

class HL{

    public:
        static HL* getInstance();
    .........
    private:
        static 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?

+6  A: 

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};
James McNellis
Thank you! It works.`boost::once_flag HL::flag = BOOST_ONCE_INIT;`
Roland Soós