Chandler Carruth in his talk on compiler optimization said that compilers are terrible at optimizing functions with parameters passed by reference. I can understand that it is difficult when parameter is a non-const reference, since the compiler has to deal with memory, or when type of the parameter is complex (some weird structure or class). But if the parameter is const reference and a builtin type are there really any problems? Can optimizer replace const float&
with const float
? It can be even more helpful when use of SSE instructions is enabled since compiler will be able properly align data for them.
const can't be optimized because there may be other mutable references to the same memory object.
Passing a parameter by const reference should be chosen where the semantics of references are actually required, or as a performance improvement only if the cost of potential aliasing would be outweighed by the expense of copying the parameter. At times, copying your parameters can also give you locality benefits.
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
Yes, you should use const whenever possible. It makes a contract that your code will not change something. Remember, a non-const variable can be passed in to a function that accepts a const parameter. You can always add const, but not take it away (not without a const cast which is a really bad idea).
Can optimizer replace
const float&
withconst float
?
No, they cannot do that, because it may change the semantic of the program. A const
reference is still a reference. It cannot be replaced by value. Consider this example:
void foo(const float& x, float a[]) {
cout << x << endl;
a[0] += 10.5;
cout << x << endl;
}
int main() {
float a[1] = { 3.25 };
foo(a[0], a);
return 0;
}
This prints
3.25
13.75
Demo 1
If you change const float&
with const float
, the result would be
3.25
3.25
Demo 2
The issue here is that a[0]
is the same as x
, but the connection is established by the caller, which is outside of optimizer's control.
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