The following base code is part of a fairly large procedure:
int x = foo();
if (x == 0) x = bar();
x doesn't change anywhere, so I could do:
const int x = foo() == 0 ? bar() : foo();
But it foo()’s a very expensive and complicated function, so I can’t name it twice because of the performance and the fact that it can generate a race condition and, therefore, get different values (this may be due to reading external resources).
I would like to make the code as readable and as short as possible. One of the options:
const int foo_ = foo(), x = foo_ == 0 ? bar() : foo_;
On the other hand, I would like to avoid this temporary variable mainly because it foo()may depend on external resources, so the use of the foo_cached value in the rest of the code is invalid.
, , , ( , , ...). !
PS: , , ++ 11, - .
, , , ( ) ( , ), .
, , ( ):
static const auto fn_zero_conditional_init = []() {
const int foo_ = foo();
return foo_ ? foo_ : bar();
};
const int x = fn_zero_conditional_init();
, , . !