Convert a macro to an inline function

I am using some Qt code that adds a VERIFY macro that looks something like this:

#define VERIFY(cond) \
{ \
    bool ok = cond; \
    Q_ASSERT(ok); \
}

Then the code can use it, at the same time being sure that the condition is really evaluated, for example:

Q_ASSERT(callSomeFunction()); // callSomeFunction not evaluated in release builds!
VERIFY(callSomeFunction());   // callSomeFunction is always evaluated

Macro rejection, instead I would like to turn this into an inline function:

inline VERIFY(bool condition)
{
  Q_ASSERT(condition);
}

However, in releases I am worried that the compiler will optimize all calls to this function (since it Q_ASSERTwill actually do nothing.) I am worried about unnecessary or, probably, depending on the flags of optimization / compiler / etc.? I think I could change it to:

inline VERIFY(bool condition)
{
  condition;
  Q_ASSERT(condition);
}

But, again, the compiler may be smart enough to ignore the call.

Is this built-in alternative safe for both debugging and release?

+3
4

, .

, - , , . , .

. , , , , .

+2

VERIFY, , , bool.

, Q_ASSERT , , , , , , .

+4

, , ! , (, - ), , , .

:

int x = Return5();
int y = PrintToConsoleAndReturn5();

// x and y never used again

Return5() ( , return 5;), , . , PrintToConsoleAndReturn5() ( ), . 5 y, . , , , , .

0

During optimization, the compiler must still respect the observed effects of the code. This means that it should support callSomeFunction()if the call is observable. (There are special exceptions that apply to copying objects around where copy deletion could be excluded - is not relevant here).

However, optimization does not matter for Q_ASSERT(callSomeFunction());in release mode. There's just nothing to optimize when the preprocessor is done, and the Q_ASSERT macro is expanded!

0
source

Source: https://habr.com/ru/post/1750296/


All Articles