c++ - 静态图添加元素成功但还是空的

标签 c++

我正在通过静态函数构建静态 unordered_map。并且在该函数中成功添加了键值对。但是,当我尝试通过直接与静态 map 交互来从 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;
}

输出:

Storing: 1, abc, Res: 1
Retrieval: [50001,abc]
Exists: 0
Lookup: Press

最佳答案

您有两个状态变量,在类内部和 registerState 函数内部。

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

更新:

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

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

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

关于c++ - 静态图添加元素成功但还是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38652977/

相关文章:

c++ - 将 C 库与 Haskell 库静态链接

c++ - 通过观察者将信号映射到插槽以获得可变数量的参数

c++ - 当 Py_initialize 失败时如何捕获并处理 fatal error ?

c++ - 声明为 Node *&ptr = root->mRight 的变量

c++ - 如何在约束中使用 ADL?

c++ - 创建 Yahtzee 游戏并遇到 Re-Roller (C++) 的问题

c++ - 如何通过 SWIG 将 lua 嵌入到 C++ 中

c++ - 从开箱即用的应用程序连接PostgreSQL的便捷方法? (嵌入PostgreSQL)

c++ - 是否有理由将无符号类型用于非负常量?

通过 Eclipse 的 c++ 和 mysql 连接器