If I do
typedef void Cb();
int foo(int const& a, Cb cb) {
int x = a;
cb();
return x - a;
}
and compile with g++ -O3 -save-temps -c foo.cpp
, I see that the subtraction is preserved, whereas if cb();
is commented out, the entire function optimizes to
xorl %eax, %eax
Is there something I can do to the specification of the parameter a
so that the subtraction will be optimized out regardless of the call to cb()
, and without forcing a
to be a unique reference (ie, that it may be referred to elsewhere, but that via none of those references will it be modified)?
A reference isn't supposed to be null. The variable must be initialized to a non-null value. The variable can never be assigned the value null . The compiler issues a warning when code assigns a maybe-null expression to a variable that shouldn't be null.
Master C and Embedded C Programming- Learn as you go Reference variable is an alternate name of already existing variable. It cannot be changed to refer another variable and should be initialized at the time of declaration and cannot be NULL. The operator '&' is used to declare reference variable.
You cannot reassign a reference.
Conceptually, C has references, since pointers reference other objects. Syntactically, C does not have references as C++ does. Wrong, conceptually pointers and references are absolutely different. Pointer is an algebraic data type of null and a reference.
There's the __restrict
extension, you can try this on gcc.godbolt.org:
typedef void Cb();
int foo(const int & __restrict a, Cb cb) {
int x = a;
cb();
return x - a;
}
Curiously, only clang does the optimization, gcc doesn't do it.
Notice that restrict-like aliasing is being considered to be part of the C++ standard:
Maybe in the future you can do it by the standard.
Doing the suggested optimization would be incorrect because the rest of the code might be:
static int var;
void func()
{
var++;
}
// ...
foo(var, func);
I'm not aware of any compiler-specific attribute you can set to say that cb()
will not modify a
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With