2

出于某种原因,我无法将值插入静态地图容器。我正在使用 VS2010,这是我的代码

Header File
class MyClass
{
    static std::map<std::string,std::string> config_map;
    static void SomeMethod();
};

Cpp File
std::map<std::string,std::string> MyClass::config_map ;

void MyClass::SomeMethod()
{
...
config_map.insert(std::pair<std::string,std::string>("dssd","Sdd")); //ERROR
}

这是我得到的错误

Unhandled exception at 0x0130ca29 in Test.exe: 0xC0000005: Access violation reading location 0x00000004.

我也试过了config_map["str"] = "something"。似乎我无法在其中插入任何内容。有什么建议么 ?

这个断点位于 xtree

_Pairib _Linsert(_Nodeptr _Node, bool _Leftish)
        {   // try to insert node at _Node, on left if _Leftish
        const value_type& _Val = this->_Myval(_Node);

        _Nodeptr _Trynode = _Root(); //Breakpoint lands here
        _Nodeptr _Wherenode = this->_Myhead;
        bool _Addleft = true;   // add to left of head if tree empty
        while (!this->_Isnil(_Trynode))
            {   // look for leaf to insert before (_Addleft) or after
            _Wherenode = _Trynode;
            if (_Leftish)
                _Addleft = !_DEBUG_LT_PRED(this->comp,
                    this->_Key(_Trynode),
                    this->_Kfn(_Val));  // favor left end
            else
                _Addleft = _DEBUG_LT_PRED(this->comp,
                    this->_Kfn(_Val),
                    this->_Key(_Trynode));  // favor right end
            _Trynode = _Addleft ? this->_Left(_Trynode)
                : this->_Right(_Trynode);
            }
4

2 回答 2

4

从评论中,您似乎正在查看静态初始化顺序 fiasco

会发生什么:无法保证不同翻译单元中静态对象的初始化顺序。你打了这个案子,这是你不想要的订单。

于 2013-05-11T20:42:20.570 回答
3

似乎在您写入地图时未正确初始化地图。static您可以将您的对象MyClass设为全局变量或静态成员,而不是制作 map 。然后在类的构造函数中初始化地图应该可以工作。

不同 .cc 文件中静态对象的初始化顺序(我猜是这种情况:写入是从另一个模块执行的)未定义。

于 2013-05-11T20:42:39.657 回答