我正在通过静态函数构建静态 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/