【问题标题】:Calling Static Member Function causes runtime error调用静态成员函数导致运行时错误
【发布时间】:2016-01-24 08:45:37
【问题描述】:

我在定义静态类变量时遇到运行时访问冲突错误。我不太确定到底出了什么问题。是我调用的静态函数在调用的时候没有实现,还是别的什么?

出了什么问题,我该如何解决?

运行时错误(请参阅下面的代码了解发生错误的行):

0xC0000005:访问冲突读取位置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"));

【问题讨论】:

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

标签: c++


【解决方案1】:

S_APP_EXIT 这样的一些静态变量依赖于其他静态变量(例如nextState)进行初始化。

阅读static initialization order fiasco 并相应地修复您的代码(使nextState 成为私有变量?)。您甚至可以考虑使用Construct On First Use Idiom(在其他常见问题解答here 中进行了解释)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多