Belov Belov - 1 month ago 12
C++ Question

Passing vector by constant value vs by constant reference

I do understand that in general there is significant difference in passing by value and reference, especially for non trivial types, and that it is mainly whether the object is copied or not, with some caveats when we have an rvalue.

However, I'm wondering whether the compiler actually recognizes that these two things are to some extend identical when the passed argument is constant, and automatically optimizes the pass by value to pass by reference? If not I assume that it is standard to make arguments passed by reference almost always, right?

Answer

No, in general the compiler can't replace a pass-by-value with a pass-by-reference, because in the general case that could introduce an aliasing problem.

The value of the argument could then change underneath the const, so to speak:

void foo( string const a, string& backarai )
{
    backarai = "Hm! ";
    backarai += a;
}

void bar( string const& a, string& backarai )
{
    backarai = "Hm! ";
    backarai += a;
}

auto main() -> int
{
    string s = "Well well well!";
    foo( s, s );    // Sets s to "Hm! Well well well!"

    string t = "Well well well!";
    bar( t, t );    // Sets t to "Hm! Hm!"
}

However, if in a specific case the compiler can prove that such aliasing won't be a problem, and that copying a string doesn't have side-effects, and so on, i.e. if it can prove that the observable program behavior in both cases will be the same, then it can optimize this way. That's just the “as if”-rule in action. It permits any optimization where the only observable change is the running time of the code.

Comments