我在定义静态类变量时收到运行时访问冲突错误。我不太确定到底出了什么问题;我正在调用的静态函数在调用时没有实现,还有别的吗?
出了什么问题,我该如何解决?
运行时错误(错误发生在下面的代码中):
0xC0000005: Access violation reading location 0x00000000.
代码:
// Status.h
class Status
{
public:
// Static Properties//
static const Status CS_SUCCESS;
// Static Functions //
static const Status registerState(const tstring &stateMsg)
{
int nextStateTmp = nextState + 1;
auto res = states.emplace(std::make_pair(nextStateTmp, stateMsg));
return (res.second) ? Status(++nextState) : Status(res.first->first);
}
private:
static std::unordered_map<STATE, tstring> states;
static STATE nextState;
};
// Status.cpp
#include "stdafx.h"
#include "Status.h"
// Class Property Implementation //
State Status::nextState = 50000;
std::unordered_map<STATE, tstring> Status::states;
const Status S_SUCCESS = Status::registerState(_T("Success"));
// IApp.h
class IApp : protected Component
{
public:
static const Status S_APP_EXIT;
static const Status S_UNREGISTERED_EVT;
...
};
// IApp.cpp
#include "stdafx.h"
#include "../EventDelegate.h"
#include "../Component.h"
#include "IApp.h"
// Class Property Implementation //
const Status IApp::S_APP_EXIT = CStatus::registerState(_T("IApp exit")); // Runtime error: 0xC0000005: Access violation reading location 0x00000000.
const Status IApp::S_UNREGISTERED_EVT = CStatus::registerState(_T("No components registered for this event"));
最佳答案
S_APP_EXIT
等一些静态变量依赖于其他静态变量(例如 nextState
)进行初始化。
了解 static initialization order fiasco并相应地修改您的代码(使 nextState
成为私有(private)变量?)。您甚至可能会想到使用 Construct On First Use Idiom(在其他常见问题解答 here 中有解释)。
无论如何,我通常不建议将所有这些变量保持静态,但很难从您发布的摘录中分辨出来(CS_SUCCESS
在哪里定义?)。
关于c++ - 调用静态成员函数导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34970614/