我正在尝试使用C++ 11的std::tr1::shared_ptr来管理SDL_Surface指针。注意,我没有使用Boost。我已经为shared_ptr定义了一个删除程序,以使用SDL_FreeSurface。
声明像:
class Engine {
private:
std::tr1::shared_ptr<SDL_Surface> _scr;
std::tr1::shared_ptr<SDL_Surface> _bg;
定义(在Engine的ctor中),例如:
_scr = std::tr1::shared_ptr<SDL_Surface>( SDL_SetVideoMode(Data::SCR_WIDTH,
Data::SCR_HEIGHT,
32, SDL_SWSURFACE),
SurfaceDeleter<SDL_Surface>());
_bg = std::tr1::shared_ptr<SDL_Surface>(IMG_Load(Data::IM_BACKGROUND),
SurfaceDeleter<SDL_Surface>());
自定义删除器:
template<typename T>
class SurfaceDeleter{
public:
void operator() (T*& d) const {
if(d){
SDL_FreeSurface(d);
}
}
};
唯一拥有shared_ptr的对象是引擎。 shared_ptr的用法如下:
SDL_BlitSurface(_bg.get(), nullptr, _scr.get(), nullptr);
SDL_Flip(_scr.get());
Valgrind结果:
==3648== 8 bytes in 2 blocks are definitely lost in loss record 16 of 292
==3648== at 0x402A018: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3648== by 0x431FBE0: strdup (in /lib/libc-2.14.1.so)
==3648== 1 bytes in 1 blocks are definitely lost in loss record 1 of 292
==3648== at 0x402A018: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3648== by 0x494A590: _XlcDefaultMapModifiers (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x494A99A: XSetLocaleModifiers (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x4097CDB: ??? (in /usr/lib/libSDL-1.2.so.0.11.3)
==3648== by 0x4083868: SDL_VideoInit (in /usr/lib/libSDL-1.2.so.0.11.3)
==3648== by 0x40594D9: SDL_InitSubSystem (in /usr/lib/libSDL-1.2.so.0.11.3)
==3648== by 0x42C3212: (below main) (in /lib/libc-2.14.1.so)
==3648== 980 (68 direct, 912 indirect) bytes in 1 blocks are definitely lost in loss record 258 of 292
==3648== at 0x402A102: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3648== by 0x49402A6: ??? (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x49407A2: ??? (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x494212F: ??? (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x49429BA: _XlcCreateLC (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x4965957: _XlcUtf8Loader (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x494A793: _XOpenLC (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x494A8F1: _XlcCurrentLC (in /usr/lib/libX11.so.6.3.0)
==3648== by 0x4097CDB: ??? (in /usr/lib/libSDL-1.2.so.0.11.3)
==3648== by 0x4083868: SDL_VideoInit (in /usr/lib/libSDL-1.2.so.0.11.3)
==3648== by 0x40594D9: SDL_InitSubSystem (in /usr/lib/libSDL-1.2.so.0.11.3)
==3648== by 0x42C3212: (below main) (in /lib/libc-2.14.1.so)
最佳答案
使用--track-origins=yes
运行valgrind,以向您显示泄漏内存的分配位置。
您可能还想使用--leak-check=full
和--leak-resolution=high
(尽管后者应为默认设置)