Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizer: replace const reference with const object

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.

like image 680
Kostya Avatar asked Dec 20 '15 13:12

Kostya


People also ask

Does const optimize?

const can't be optimized because there may be other mutable references to the same memory object.

Why should we use const references for function parameters rather than pass by value?

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.

Can you modify a const reference C++?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.

Should I always use const reference?

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).


1 Answers

Can optimizer replace const float& with const 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.

like image 145
Sergey Kalinichenko Avatar answered Oct 20 '22 13:10

Sergey Kalinichenko