Followers 0

# conditional statement + automatic clean-up in preprocessor command

## 8 posts in this topic

Hello,

I wish to have a conditional statement, followed immediately by an object instanciation that will automatic clean-up at the end of a scope, a little bit similar to following example:

if (conditionRealized)
{
// do something
}

which effectively would translate into something like:

if (conditionRealized)
{
DummyObject dummy(initializationType);
// do something
}

in above example, the destructor of dummy can automatically clean-up various things.

I have to place such a construct into several hundreds of functions, and I wish to simplify the task with a preprocessor command, so that I will be able to write:

IF_CONDITION_REALIZED_THEN
{
// do something
}

but above construct does obviously not work, since the scope comes after the preprocessor command.

I could use a preprocessor like:

#define IF_CONDITION_REALIZED_THEN if(conditionRealized) { DummyObject dummy(initializationType);

in order to write my code like:

IF_CONDITION_REALIZED_THEN
// do something
}

but my code editor doesn't like this (puts wrong indents), and it looks ugly.

Any idea?

Or, to present my problem in a different light:

I have a condition, that if passed, needs to make sure something is executed at the end of the scope, similar to this example:

if (canLockOtherThreads())
{
// do something
}
Edited by floatingwoods
0

##### Share on other sites

Thanks to both of you, that's briliant!

0

##### Share on other sites

Why not just put that 'special condition' in the object destructor instead?

Or just code a normal function for that???

Edited by Vortez
1

##### Share on other sites
Just a note that all the above suggestions (the for loop back, etc.) are not exception safe.

As a general rule, I'd advise against this kind of macro. It's non-idiomatic, error prone and difficult to debug.

C++ already has a perfectly valid cleanup mechanism in RAII. Trust me, saving a bit of typing is just not worth it

Edit: oops, missed servants post. That is exception safe, still wouldn't use the macro though.
1

##### Share on other sites

A lot of good ideas, thanks a lot to all of you!

0

## Create an account

Register a new account