2016-01-24 107 views
2

定义静态类变量时出现运行时访问冲突错误。我不太确定究竟发生了什么问题;是我调用的静态函数在调用时没有实现,还有其他的东西?调用静态成员函数会导致运行时错误

怎么回事,我该如何解决这个问题?

运行时错误(见下文代码发生在错误的行):

0000005:访问冲突读取位置00000000。

代码:

// 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")); 
+3

有两件事:1)你是否使用过调试器来调试你的应用程序,如果没有,为什么不呢? 2)不要发布无法自行编译的代码的各种随机部分,而需要发布一个最小化,完整,可验证的示例,请参阅http://stackoverflow.com/help/mcve以获取更多信息。我没有在您的问题中看到任何特定于Microsoft Windows平台的问题,因此您的最小,完整,可验证示例必须可在任何平台上编译和执行。 –

回答

1

一些静态变量,如S_APP_EXIT取决于其初始化其他静态变量(例如nextState)。

阅读关于static initialization order fiasco并相应地修复您的代码(使nextState成为一个私有变量?)。你甚至可以考虑使用构建首先使用成语(解释在其他常见问题here)。

无论如何,我通常不会建议保持所有这些变量是静态的,但很难从您发布的摘录中分辨出来(CS_SUCCESS定义在哪里?)。

相关问题