我目前正在编写代码以从 NSView 获取 OpenGL 纹理。该代码主要是 Apple 示例代码。但是,我需要在 C++ 类中使用它,并且我遇到了泄漏对象的问题。
这是代码中有趣的部分:
GLuint CPlusPlusClass::openGLTexFromNSView(NSView* theView)
{
GLuint texName = 0x0;
@autoreleasepool // 1
{ // 1
NSBitmapImageRep* bitmap = [theView bitmapImageRepForCachingDisplayInRect:[theView visibleRect]];
int samplesPerPixel = 0;
[theView cacheDisplayInRect:[theView visibleRect] toBitmapImageRep:bitmap];
samplesPerPixel = (int)[bitmap samplesPerPixel];
glPixelStorei(GL_UNPACK_ROW_LENGTH, (int)([bitmap bytesPerRow]/samplesPerPixel));
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
glGenTextures (1, &texName);
glBindTexture (GL_TEXTURE_RECTANGLE_ARB, texName);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
if(![bitmap isPlanar] && (samplesPerPixel == 3 || samplesPerPixel == 4))
{
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0,
samplesPerPixel == 4 ? GL_RGBA8 : GL_RGB8,
(int)[bitmap pixelsWide], (int)[bitmap pixelsHigh],
0, samplesPerPixel == 4 ? GL_RGBA : GL_RGB,
GL_UNSIGNED_BYTE, [bitmap bitmapData]);
}
} // 1
return texName;
}
当我将视图绘制到 OpenGL 上下文并在 Activity Monitor 中检查应用程序的内存占用时,我看到每次 Activity Monitor 的视图刷新时该数字都会增加约 4 MB。通过添加代码中@autoreleasepool
指示的块//1
,我可以将它降低到每个刷新周期大约 2 MB。尽管如此,它仍在不断增加。
从 C++ 中释放自动释放对象的正确方法是什么?