静态地图成功添加元素但仍为空

时间:2016-07-29 07:30:12

标签: c++

我正在通过静态函数构建静态unordered_map。并且在该函数中成功添加了键值对。但是当我尝试通过直接与静态地图交互从地图中检索值时,它不包含该值?

出了什么问题,我该如何解决?

在Status.h中:

typedef int STATE;
typedef std::string tstring;

class Status
{
public:

    static Status registerState(const tstring &stateMsg);
    explicit Status(const STATE &state);
    const STATE state;

    static std::unordered_map<STATE, tstring> states;
    static STATE nextState;
};

在Status.cpp中:

// Class Property Implementation //
STATE Status::nextState;
std::unordered_map<STATE, tstring> Status::states;

// Static Function Implementation //
Status Status::registerState(const tstring &stateMsg)
{
    // Initialise here to avoid the "static initialisation order fiasco"
    static STATE nextState = 50000;
    static std::unordered_map<STATE, tstring> states;

    // absence of the above causes runtime error upon emplacing the value
    // Error: Unhandled exception at 0x0125D326 in TestCBA.exe: 0xC0000005: Access violation reading location 0x00000000.

    int nextStateTmp = nextState + 1;
    auto res = states.emplace(std::make_pair(nextStateTmp, stateMsg));
    printf("Storing: %d, %s, Res: %d\n", states.size(), stateMsg.c_str(), res.second);
    printf("Retrieval: [%d,%s]\n", nextStateTmp, states[nextStateTmp].c_str());

    return (res.second) ? Status(++nextState) : Status(res.first->first);
}

// Function Implementation //
Status::Status(const STATE &state) : state(state)
{

}

在main.cpp中:

int main(int argc, char** argv)
{
    Status s1 = Status::registerState("abc");

    printf("Exists: %d\n", Status::states.find(s1.state) != Status::states.end());
    printf("Lookup: %s\n", Status::states[s1.state].c_str());
    system("PAUSE");
    return 0;
}

输出:

  

存储:1,abc,Res:1
  检索:[50001,abc]
  存在:0
  查找:按

1 个答案:

答案 0 :(得分:4)

在类中和registerState函数内部有两个states变量。

在main的第一行中,您调用函数来存储一个新元素,该元素插入到函数内的对象中。然后,此函数显示结果:Storing: 1。然后,在main的第二部分中,使用类的静态对象,它是空的。

更新:

当在文件中定义时(类定义下方),类的变量由构造函数初始化。将此变量视为全局变量,但在类范围内。

第二个也是一个全局变量,但只在函数内部已知。第一个在构造函数中初始化,作为全局变量。第二个是在对函数的第一次调用中初始化的。

由于初始化问题的顺序,你可能会感到困惑。在您的情况下,此问题并不重要,因为只有全局变量的初始化顺序影响最终结果时才会出现此问题。我猜你已经找到了一些与在函数内包含对象(作为静态对象)相关的解决方案,以确保顺序合适。在这个解决方案中,类中的静态对象将是desspear。