我有以下类定义:
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-catch:
try
{
mDisplay = &display;
}
catch(const std::exception&)
{
// Couldn't reach this code.
}
当我尝试这样做时,最奇怪的事情发生了。我得到了完全相同的异常,它在包含try
...
编辑2:
链接到al_create_display()上的文档。它将原始指针返回到显示器。
编辑3:
我怀疑是导致问题的原因是赋值运算符。因此,我尝试将ALLEGRO_BITMAP *mDisplay
替换为std::vector<ALLEGRO_BITMAP *>
,而没有做mDisplay = &display
,而是做了mDisplay.push_back(&display)
。现在,异常消失了。如果有人能给予更多启示,我真的很感激。可能是复制分配运算符被禁用了吗?
答案 0 :(得分:0)
希望这可以帮助您查看以下评论:
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