首页 > 解决方案 > 多次返回时清理内存 - 函数 C++

问题描述

我正在使用具有多个返回路径的函数。但是在它们中的每一个上,我都需要清理内存,释放一些对象等。我在互联网上看到了一些方法,但我认为它们不是“标准”甚至是防故障(goto声明)。我相信这是一种常见的情况,它可能对其他有同样问题的人有用。

这是一个例子:

//Opening many handles//
//.....

//The actual code
void *imgBytes;
bmp = CreateDIBSection(memHDC, &bmpInfo, DIB_RGB_COLORS, &imgBytes, NULL, NULL);
HGDIOBJ oldSelect = SelectObject(memHDC, bmp);


BitBlt(memHDC, 0, 0, screenW, rowHeight, screen, 0, yOffset, SRCCOPY);
GdiFlush();

//Memory leaks
if(!condition1) return false;
if(!condition2) return false;
if(!condition3) return false;
if(!condition4) return false;
if(!condition5) return false;
if(!condition6) return false;


//Code to be executed on every return
SelectObject(memHDC, oldSelect);
DeleteDC(memHDC);
DeleteObject(bmp);
ReleaseDC(NULL, screen);

这个问题的一种解决方案可能只是将每个插入if另一个(但我没有解决问题):

if(condition1){
    if(condition1){
        if(condition1){
            if(condition1){
                //continue execution...
                return true;
            }
        }
    }
}


//One of the conditions above failed. Clean code
SelectObject(memHDC, oldSelect);
DeleteDC(memHDC);
DeleteObject(bmp);
ReleaseDC(NULL, screen);

return false;

我怎样才能解决这个问题,但没有goto's.

标签: c++returncode-cleanup

解决方案


推荐阅读