Reputation: 25928
I am getting a runtime access violation error when defining a static class variable. I'm not quite sure what is exactly going wrong; is the static function I am calling not implemented at the time of calling, something else?
What is going wrong and how can I fix this?
Runtime error (see code below for the line that the error occurs on):
0xC0000005: Access violation reading location 0x00000000.
Code:
// 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"));
Upvotes: 2
Views: 603
Reputation: 43662
Some static variables like S_APP_EXIT
depend on other static variables (e.g. nextState
) for their initialization.
Read about the static initialization order fiasco and fix your code accordingly (making nextState
a private variable?). You might even think of using the Construct On First Use Idiom (explained in the other FAQ here).
Anyway I wouldn't generally advise keeping all those variables static, but it's quite hard to tell from just the excerpt you posted (where is CS_SUCCESS
defined?).
Upvotes: 1