I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like:
WARN(
"Danger Will Robinson! There are "
+ boost::lexical_cast<string>(minutes)
+ " minutes of oxygen left!"
);
I'm using an inline function for WARN, but I'm curious as to how much optimization is going on behind the scenes -- evaluation of the arguments throughout the entire program would be costly. The WARN
function goes something like this:
bool WARNINGS_ENABLED = false;
inline void WARN(const string &message) {
if (!WARNINGS_ENABLED) {
return;
}
// ...
}
Given that constructing the string argument has no side-effects, will the compiler optimize it out? Is a certain level of optimization required (-Ox
in g++
for some x
)?
If you need to be able to selectively enable and disable the warnings at run-time, the compiler will not be able to optimize out the call.
What you need is to rename your function to WARN2
and add a macro something like:
#define WARN(s) do {if (WARNINGS_ENABLED) WARN2(s);} while (false)
This will prevent the evaluation of s at run-time unless you have warnings enabled.
The do-while stuff is a trick that allows it to be used anywhere in the code (naked statement, statement within a braced if-block, statement within an unbraced if-block, braced and unbraced while statements and so on).