c++ - 多次返回时清理内存 - 函数 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
.
解决方案
推荐阅读
- web-scraping - Google 表格:从 IMPORTDATA() 中拆分多行分隔文本
- python - 如何检测 Tkinter 中单击的按钮在哪一帧上?
- swift - SwiftUI 新手:绑定、切换和致命错误:索引超出范围
- notepad++ - SRT 文件问题(索引和空行)
- python - Python:IndexError:修改代码后列表索引超出范围
- c - 给定区间之间的质数
- typescript - 当同一接口上存在其他属性(字符串文字)时,有条件地使类型成为必需
- python - Keras Sequential:创建 Tensorflow numeric_columns 的优势?
- webclient - 使用 Spring 5 WebClient 是否可以使用 GET 请求类型发送 JSON 正文?
- c# - WSO2 IS 5.10 自动解锁在锁定时间后不起作用