If I have two different constant members variables, which both need to be initialized based on the same function call, is there a way to do this without calling the function twice?
For example, a fraction class where numerator and denominator are constant.
int gcd(int a, int b); // Greatest Common Divisor
class Fraction {
public:
// Lets say we want to initialize to a reduced fraction
Fraction(int a, int b) : numerator(a/gcd(a,b)), denominator(b/gcd(a,b))
{
}
private:
const int numerator, denominator;
};
This results in wasted time, as the GCD function is called twice. You could also define a new class member, gcd_a_b
, and first assign the output of gcd to that in the initializer list, but then this would lead to wasted memory.
In general, is there a way to do this without wasted function calls or memory? Can you perhaps create temporary variables in an initializer list?
-O3
. But probably for any simple test implementation it would actually inline the function call. If you use__attribute__((const))
or pure on the prototype without providing a visible definition, it should let GCC or clang do common-subexpression elimination (CSE) between the two calls with the same arg. Note that Drew's answer works even for non-pure functions so it's much better and you should use it any time the func might not inline. – Peter Cordes