早期调用了C++析构函数
C++ destructor called early
我有一个为我管理SDL_Surface的类,我想创建它,这样我就不必担心释放曲面了。到目前为止,我有这个代码:
//In Entity.h
class Entity
{
public:
int x, y, width, height;
Entity(std::string);
~Entity();
void render();
private:
SDL_Surface* texture;
};
//In Entity.cpp
Entity::~Entity()
{
printf("Destroying an Entity");
SDL_FreeSurface(texture);
}
//In main.cpp
Entity puppy("puppy.bmp");
void render() {
clearScreen();
puppy.render();
}
int main (int argc, char **argv) {
printf("started");
init();
bool done = false;
while(!done)
{
...
// Draw the screen
printf("About to render");
render();
SDL_Flip(screen);
}
SDL_Quit();
return 0;
}
当我运行它时,我得到了Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000260
0x000000010002fd9b in SDL_DisplayFormat ()
。我认为析构函数被提前调用,并且它试图渲染NULL纹理,这是正确的吗?如果我没有析构函数,只是浪费内存,代码就可以正常工作。我也尝试过将小狗作为局部变量并将其传递给渲染器,但这并没有帮助。
编辑:代码只运行一秒钟,然后崩溃。它不等待退出循环。此外,通过gdb的程序显示,由于某种原因,小狗至少被画了一次。我在这里上传了完整的来源:http://dl.getdropbox.com/u/2223161/sdlgame.zip
这是一个全局变量:
Entity puppy("puppy.bmp");
它在main()
结束后被销毁,所以SDL_FreeSurface
在SDL_Quit()
之后被调用。它有效吗?查看文档。
您看到的是问题的错误一端。在我将puppy
的初始化移动到main
之后,您的代码为我运行。
通过将puppy
放置为全局对象,其构造函数在SDL_Init
之前运行。构造函数调用load_image
,后者调用SDL_DisplayFormat
。文件警告:
在使用
SDL_DisplayFormat
函数之前,您必须调用SDL_Init
。如果不这样做,您的程序将因访问违规而崩溃。
http://sdl.beuc.net/sdl.wiki/SDL_DisplayFormat
当然,您还应该确保析构函数在SDL_Quit()
之前被调用,这是正确的,尽管这不是目前导致访问冲突的原因。
- 什么时候调用组成单元对象的析构函数
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 什么时候调用析构函数
- 优先顺序:智能指针和类析构函数
- C++-明确何时以及如何调用析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 在c++中使用向量时,如何调用构造函数和析构函数
- 重载运算符new[]的行为取决于析构函数
- 我需要知道编译器如何在cpp中使用析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 析构函数调用
- 通过引用传递-为什么要调用这个析构函数
- 对具有动态分配的内存和析构函数的类对象的引用
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- C++成员的析构函数顺序与shared_ptr
- C++ 防止在映射中放置()时调用析构函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 调用析构函数以释放动态分配的内存
- 不命名构造函数和析构函数上的类型错误