2

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 .

6
  • 13
    RAII Commented Apr 24, 2019 at 15:27
  • 1
    This scenario is one of the main reasons modern exception handling has become popular. Your main choices are gotos, or copy the cleanup code - or RAII, as @Nathan suggests (which is really implicit exception handling). Commented Apr 24, 2019 at 15:27
  • 5
    Use RAII! It's one of the best things about C++ and you would benefit greatly from it. You can wrap your resources in classes or helpers like unique_ptrs that do the cleanup work automatically and seamlessly. In a sense, you can forget about cleanup entirely using RAII. Commented Apr 24, 2019 at 15:29
  • 2
    You can use std::unique_ptr with custom deleter Commented Apr 24, 2019 at 15:31
  • 2
    "I will also check RAII" using std::unique_ptr or custom class is actually RAII, just using std::unique_ptr is simpler and cleaner as it requires less code written and that class disabled possible ways of leaking the resource it manages Commented Apr 24, 2019 at 15:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.