0

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?

Alex Botev
  • 1,369
  • 2
  • 19
  • 34

1 Answers1

1

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • I presume that when all arguments are constant than this would be the case. – Alex Botev Oct 26 '16 at 01:22
  • Yes. But it would still have to prove that e.g. copying a string doesn't have side effects. Since `std::string` is provided by the compiler vendor, that is quite possible, but I don't know whether it's done or not. – Cheers and hth. - Alf Oct 26 '16 at 01:23
  • Yeah you might be right there. In my case I'm dealing with vectors, but any way it was good to know. – Alex Botev Oct 26 '16 at 01:35