返回指向同一个变量的指针会泄漏内存吗?
Does returning a pointer to the same variable leaks memory?
此代码是否泄漏内存?
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);
}
我每次分配变量之前都需要销毁(从内存中清除)表面和纹理吗?
在 C++ 中导致内存泄漏的 唯一 是 new
与 delete
或 new[]
不平衡与 delete[]
不平衡。 (此外,如果您使用 malloc
等,那么您 必须 使用 free
。)
在你的情况下,它看起来像 IMG_Load
和 SDL_CreateTextureFromSurface
do 分配内存,所以是的,我会说它确实泄漏。请查阅函数文档以了解您需要如何管理分配的任何内存的释放。通常,如果库分配内存,那么它会提供释放内存的方法。这是因为内存管理是由 C++ 运行时完成的,并且可能因编译而异。
是的。 SDL_CreateTextureFromSurface
has a corresponding SDL_DestroyTexture
and SDL_FreeSurface
个必须调用的方法。
SDL_CreateTextureFromSurface
页面上的注释
The surface is not modified or freed by this function.
根据@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.
为了加分,您可以在 namespace std
中添加 std::default_delete<T>
的特化处理 SDL_****
指针并避免单独声明删除器。
是的。您应该使用 SDL_FreeSurface 函数释放内存。
在这种情况下我建议使用智能指针来释放内存'automatically':
std::unique_ptr<SDL_Surface, decltype(&SDL_FreeSurface)> surface{IMG_Load(path.c_str()), SDL_FreeSurface};
要访问智能指针,请使用:
surface.get()
此代码是否泄漏内存?
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);
}
我每次分配变量之前都需要销毁(从内存中清除)表面和纹理吗?
在 C++ 中导致内存泄漏的 唯一 是 new
与 delete
或 new[]
不平衡与 delete[]
不平衡。 (此外,如果您使用 malloc
等,那么您 必须 使用 free
。)
在你的情况下,它看起来像 IMG_Load
和 SDL_CreateTextureFromSurface
do 分配内存,所以是的,我会说它确实泄漏。请查阅函数文档以了解您需要如何管理分配的任何内存的释放。通常,如果库分配内存,那么它会提供释放内存的方法。这是因为内存管理是由 C++ 运行时完成的,并且可能因编译而异。
是的。 SDL_CreateTextureFromSurface
has a corresponding SDL_DestroyTexture
and SDL_FreeSurface
个必须调用的方法。
SDL_CreateTextureFromSurface
The surface is not modified or freed by this function.
根据@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.
为了加分,您可以在 namespace std
中添加 std::default_delete<T>
的特化处理 SDL_****
指针并避免单独声明删除器。
是的。您应该使用 SDL_FreeSurface 函数释放内存。
在这种情况下我建议使用智能指针来释放内存'automatically':
std::unique_ptr<SDL_Surface, decltype(&SDL_FreeSurface)> surface{IMG_Load(path.c_str()), SDL_FreeSurface};
要访问智能指针,请使用:
surface.get()