2010-09-08 36 views
0

VERSION 1插入「本」到從構造函數的STL地圖

 
class Doh { 
private: 
    static std::map<const std::string, const Doh*> someMap; 
    std::string stringValue_; 
public: 
    Doh(std::string str) : stringValue_(str) { 
     Doh::someMap.insert(
      std::make_pair<const std::string,const Doh*> 
       (this->stringValue_,this) 
     ); 
    } 
} 

以上是確定與2010年MSVC,但與2008年MSVC失敗 - 我想這是因爲對象尚未在構建它被插入到地圖中(我得到了內存訪問衝突)。

所以,我嘗試了延遲插入,它的工作:

VERSION 2

 
Doh(std::string str) : stringValue_(str) { 
    boost::thread(&Doh::insertIntoTheStaticMap,this); 
} 
void insertIntoTheStaticMap() { 
    boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); 
    Doh::someMap.insert(
     std::make_pair<const std::string,const Doh*> 
      (this->stringValue_,this) 
    ); 
}
但你也許能猜到,我的意圖是讓 靜態衛生署:: someMap作爲共同查找字典。

VERSION 1並不需要任何線程安全的,因爲我會在同一個線程創建所有衛生署實例 - 在初始化塊 - 這將通過動態初始化之前,我進入主()被調用。

但隨着版本2中,天真的睡眠()既不優雅,也不可靠的(更不用提,我可能需要插入之前鎖定的地圖)。

什麼是一個很好的KISS方法?

+0

也許你可以展示更多版本的代碼。這不應該有任何問題。地圖的類型是什麼? 'this-> stringValue_'的類型是什麼?你還有什麼使用地圖? – 2010-09-08 18:39:45

+0

匆忙我已經刪除了更多的代碼,然後我應該...我編輯了這篇文章。感謝您的快速週轉 – 2010-09-08 19:41:33

+0

仍然缺少'map'參數。 – Potatoswatter 2010-09-08 19:49:47

回答

1

我只看到潛在的問題是static成員的初始化,如果有多個源文件。嘗試用一個函數來保護它。

class Doh { 
private: 
    static std::map< std::string, Doh * > &get_map() { 
     static std::map< std::string, Doh * > someMap; 
     return someMap; // initialize upon first use 
    } 
    std::string stringValue_; 
public: 
    Doh(std::string str) : stringValue_(str) { 
     get_map().insert(
      std::make_pair 
       (this->stringValue_,this) 
     ); 
    } 
}; 
+0

這工作 - 我認爲靜態初始化器總是在動態初始化器之前。 – 2010-09-08 20:19:20

0

在既不版本是有stringvalue_初始化的跡象 - 這是什麼調試器告訴你關於這個關鍵當你點擊地圖插入代碼的1.0版本?這個字段是如何設置的,它的類型是什麼?

在調試器VS2008應該讓你縮小故障點到<map>源運行這個,我還以爲。