将“this”插入构造函数的STL映射中

时间:2010-09-08 18:36:43

标签: visual-c++ stl constructor insert map

版本1

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

以上对MSVC 2010来说没问题,但是MSVC 2008失败了 - 我想这是因为当对象插入地图时我没有构建对象(我有内存访问冲突)。

所以,我尝试了延迟插入,这有效:

版本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)
    );
}
但正如您可能猜到的那样,我的意图是将静态Doh :: someMap 作为常见的查找字典。

VERSION 1不需要任何线程安全性,因为我会在同一个线程中创建所有Doh实例 - 在初始化块中 - 在我进入main()之前由动态初始化器调用。

但是对于VERSION 2,天真的睡眠()既不优雅也不可靠(更不用说,我可能需要在插入之前锁定地图)。

什么是一个很好的KISS方法?

2 个答案:

答案 0 :(得分: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)
        );
    }
};

答案 1 :(得分:0)

在两个版本中都没有stringvalue_的init符号 - 当您在代码的版本1中点击地图插入时,调试器会向您显示有关此键的信息?该字段是如何设置的,它的类型是什么?

在VS2008的调试器中运行它应该允许您将故障点缩小到<map>来源,我原以为。