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方法?
也許你可以展示更多版本的代碼。這不應該有任何問題。地圖的類型是什麼? 'this-> stringValue_'的類型是什麼?你還有什麼使用地圖? – 2010-09-08 18:39:45
匆忙我已經刪除了更多的代碼,然後我應該...我編輯了這篇文章。感謝您的快速週轉 – 2010-09-08 19:41:33
仍然缺少'map'參數。 – Potatoswatter 2010-09-08 19:49:47