Is there any performance boost in storing the return value of a function by reference? I mean is the following code preferred because it prevents copying the return value of function into the variable?
string Foo()
{
string someString = "some string";
return someString;
}
const string &str = Foo();
Edit: Although in the above example Foo() is returning a string, my question concerns returning other type of objects as well.
Your code as it stands contains two copies in
Foo:(1) from a temporary object of type
stringconstructed using theconst char*constructor, tosomeString.(2) from the variable
someStringto the temporary object that is the return value ofFoo.You are writing
const string &str = Foo();instead ofconst string str = Foo();with the intention of preventing a third copy:(3) from the temporary object that is the return value of
Foo, tostr.All three copies are permitted by the standard to be elided, so the question basically is whether your compiler needs help with 3.
As a rule of thumb I would say no — if your compiler is smart enough to elide copies 1 and 2, then likely it is smart enough to elide 3. If it is not smart enough to elide any of them, and this costs you performance, then you need to work on function
Fooas well as on code that calls it. But this situation won’t come up — as long as you remember to turn on optimization, any real C++ compiler can do copy elision.There could conceivably be special cases where you need to write your code carefully to help the compiler out where it fails to elide some copy that it is permitted to elide. You need to find those cases as they occur, no general coding guideline can (accurately) tell you that you need to worry about (3) but not (1) and (2).