Valhalla Legends Forums Archive | Advanced programming | Augmenting C++ with macros

AuthorMessageTime
EibroIf you were to dig deeper into the language features, I don't think you would be having these problems. Ever hear of Resource Acquisition Is Initialization, or the Scoped Lock idiom?

Wouldn't it be cool if you could do this (or something similar)?

typedef basic_auto_handle< HANDLE, CloseHandle > auto_handle;

void fn() {

   auto_handle h = CreateFile( ... );
   auto_handle h2 = CreateFileMapping( ... );
}

Now the destructors of h and h2 will clean anything up that needs to be cleaned. Even in the face of exceptions, resources will still be freed. I don't agree with what you cited: http://www.joelonsoftware.com/items/2003/10/13.html. If you're writing exception safe code from the start, it doesn't matter how many possible "invisible" exit points there are. See Herb Sutter's Exceptional C++, and More Exceptional C++ for some in depth examples of writing exception safe code.
May 25, 2005, 10:43 am
Arta[vL]Ooh, that is nice. I'll have to have a play. I still don't like exceptions much though TongueMay 25, 2005, 11:34 am
tA-Kane
Code:
// do something
// do something2
if(!something2)
{
free(something);
}

// do something3
if(!something3)
{
free(something);
free(something2);
{

// do something4
if(!something4)
{
free(something);
free(something2);
free(something3);
}

Or:

Code:

// do something
if(something)
{
// do something2
if(something2)
{
// do something3
if(something3)
{
// something4
if(something4)
{
// something 5
}
else
{
free(something);
free(something2);
free(something3);
}
}
else
{
free(something);
free(something2);
}
}
else free(something);
}
I completely agree with Adron. Too many people underestimate the value of the goto keyword. And in fact, a lot of common new languages don't even provide one, which is quite frustrating to me. *cough*PHP? Java?*cough* It's one of the reasons I quite dislike web programming.
A goto seems safer.

In any case, here's how I would do what you're asking, which looks nice in my opinion:
Code:
//do something
if (!something) goto finally;

//do something2
if (!something2) goto finally;

// do something3
if (!something3) goto finally;

// do something4
if (!something4) goto finally;


finally:
if (something) free something;
if (something2) free something2;
if (something3) free something3;
if (something4) free something4;
May 25, 2005, 04:50 pm
Arta[vL]Yes, this is the one acceptable use of goto, imho Smiley

Nonetheless, I still don't exactly like goto, and a more structured way to do this would be nice. Perhaps I should email Bjarne Stroustrup Smiley
May 30, 2005, 12:20 pm
KpWhat about this?

Code:
act1;
if (ok(a1)) {
    act2;
    if (ok(a2)) {
        act3;
        if (ok(a3)) {
            return; /* or goto out */
        } /* assume failure of act3 means it doesn't need to be freed */
        free(act2);
    }
    free(act1);
}
May 30, 2005, 12:24 pm