I am using a function with multiple return paths. But on every one of them I need to clean the memory,release some objects,etc. I have seen on the internet some methods but I don't think they are "standard" or even fail-proof (goto statements). I believe this is a common situation and it may prove useful for others with same the same problem.
Here's an example:
//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);
One solution to this problem could be just to insert every if inside another(but I doesn't solve the problem):
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;
How can I solve this problem but without goto's .
unique_ptrs that do the cleanup work automatically and seamlessly. In a sense, you can forget about cleanup entirely using RAII.std::unique_ptrwith custom deleterstd::unique_ptror custom class is actually RAII, just usingstd::unique_ptris simpler and cleaner as it requires less code written and that class disabled possible ways of leaking the resource it manages