此代码是否会泄漏内存?
SDL_Texture* texture;
SDL_Surface* surface;
int infinity = 99999999;
for (int i=0; i<infinity; i++) {
surface = IMG_Load("path/to/image.png");
texture = SDL_CreateTextureFromSurface(renderer, surface);
}
在重新分配变量之前,我是否需要每次都消除(从内存中清除)表面和纹理?
答案 0 :(得分:5)
是。 SDL_CreateTextureFromSurface
具有必须调用的相应SDL_DestroyTexture
和SDL_FreeSurface
方法。
请注意SDL_CreateTextureFromSurface
此功能不会修改或释放曲面。
根据@bathsheba,可以使用std::unique_ptr
进行删除。
auto SDLTextureDeleter = [](SDL_Texture* pTexture) { if(pTexture) SDL_DestroyTexture(pTexture); };
std::unique_ptr<SDL_Texture, decltype(SDLTextureDelter)>(texture, SDLTextureDeleter); // This will call SDL_DestroyTexture when the unique pointer is destructed.
对于奖励积分,您可以在std::default_delete<T>
中为处理namespace std
指针的SDL_****
添加专精,并避免单独声明删除。
答案 1 :(得分:1)
在C ++中导致内存泄漏的唯一事件是new
,与delete
或new[]
不平衡delete[]
。 (另外,如果您使用malloc
&amp; c。,则必须使用free
。)
在您的情况下看起来像IMG_Load
和SDL_CreateTextureFromSurface
做分配内存,所以是的我会说它确实泄漏了。查阅功能文档,了解如何管理分配的任何内存的释放。通常,如果库分配内存,那么它提供了释放它的方法。这是因为内存管理由C ++运行时完成,并且可以在编译和编译之间变化。
答案 2 :(得分:0)
是的。您应该使用SDL_FreeSurface函数释放内存。
在这种情况下,我建议使用智能指针“自动”释放内存:
std::unique_ptr<SDL_Surface, decltype(&SDL_FreeSurface)> surface{IMG_Load(path.c_str()), SDL_FreeSurface};
要使用智能指针,请使用:
surface.get()