繁体   English   中英

内存位置的Microsoft C ++异常runtime_error(代码0x75A818A2)

[英]Microsoft C++ exception runtime_error at memory location (Code 0x75A818A2)

我有以下类定义:

class DisplayManager
{
public:
    static DisplayManager *getInstance();
    DisplayManager(DisplayManager const&) = delete;
    void operator=(DisplayManager const&) = delete;
    ~DisplayManager();

    void addDisplay(ALLEGRO_DISPLAY &display);
private:
    DisplayManager();

    ALLEGRO_DISPLAY *mDisplay = nullptr;
};

该类的实现是:

DisplayManager *DisplayManager::getInstance()
{
    static DisplayManager instance;
    return &instance;
}

DisplayManager::~DisplayManager()
{}

void DisplayManager::addDisplay(ALLEGRO_DISPLAY &display)
{
    if(!mDisplay)
    {
        throw std::runtime_error("Failed to create display: A display is already created.");
    }

    mDisplay = &display;
}

DisplayManager::DisplayManager()
{
}

addDisplay()方法由另一个类调用,如:

void Display::createDisplay()
{
    auto *manager = DisplayManager::getInstance();

    if(!manager)
    {
        throw std::runtime_error("No diplay manager.");
    }

    ALLEGRO_DISPLAY *display = al_create_display(width, height);

    if(!display)
    {
        throw std::runtime_error("Failed to create display");
    }

    manager->addDisplay(*display);
}

addDisplay()方法中,当我做mDisplay = &display; ,我得到以下异常:

Unhandled exception at 0x75A818A2 in My_Executable.exe: Microsoft C++ exception: std::runtime_error at memory location 0x0073F66C.

尽管存在此异常,应用程序仍按预期工作。 我无法弄清楚这个例外的原因。

编辑1:

我试着试试看:

try
{
    mDisplay = &display;
}
catch(const std::exception&)
{
// Couldn't reach this code.
}

当我尝试这个时,最奇怪的事情发生了。 我得到完全相同的异常,并在包含try的行中引发...

编辑2:

链接到al_create_display()的文档。 它返回一个指向显示的原始指针。

编辑3:

我怀疑它是导致问题的赋值运算符。 所以我尝试用std::vector<ALLEGRO_BITMAP *>替换我的ALLEGRO_BITMAP *mDisplay ,而不是做mDisplay = &display ,我做了mDisplay.push_back(&display) 现在,异常消失了。 如果有人能够透露更多的光,我真的很感激。 可能是复制赋值运算符被禁用了吗?

希望这可以帮助您看到以下评论:

void DisplayManager::addDisplay(ALLEGRO_DISPLAY &display)
{
    if(!mDisplay)
    {
        throw std::runtime_error("Failed to create display: A display is already created.");
    }

    mDisplay = &display; // dangerous to do this, mDisplay point to display
//if display is being destroy => mDisplay point to un-legal memory
}

看看我们称之为的地方

ALLEGRO_DISPLAY *display = al_create_display(width, height); // problem in here
 //if this function return object which will being destroyed later, then error happen

if(!display)
{
    throw std::runtime_error("Failed to create display");
}

manager->addDisplay(*display); // look at this, when we are out of this 
//and the object above is being destroy, mDisplay point to un-legal memory => exception

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM