2010-03-31 33 views
2

我嘗試創建一個多線程單例模式類。Boost C++單例錯誤LNK2001:無法解析的外部符號「private:static long Nsp :: HL :: flag」(?flag @ HL @ Nsp @@ 0JA)

頁眉:

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(); 
} 

我得到這個錯誤:

 
error LNK2001: unresolved external symbol "private: static long Nsp::HL::flag" ([email protected]@[email protected]@0JA) 

有什麼不對?

回答

7

您需要定義在CPP文件中的靜態成員變量:

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

,如果你需要(我沒有用boost::once_flag可以初始化它,不能告訴你是否它需要如何初始化):

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

謝謝!有用。 'boost :: once_flag HL :: flag = BOOST_ONCE_INIT;' – 2010-03-31 01:04:28

相關問題