Contrary to popular belief, there is no guarantee that assigning the result of a function that returns an object by value to a const reference will result in fewer copies than assigning it to the object itself.
When you assign an rvalue to a const link, the compiler can link the link in one of two ways. He can create a new temporary one by copying the rvalue and linking the link to it, or he can bind the link directly to the rvalue itself.
If the compiler cannot do the βobviousβ optimization to remove the temporary and hide the copy constructor for the getFoo return value, how likely is it to be able to make a more efficient form of binding the r value for the const link without creating a new temporary?
One reason for using a constant reference would be to make the function more resistant to potential slicing. If the return type was actually a type obtained from Foo , then assigning a const const reference would be guaranteed not to be truncated, even if the compiler made a temporary object from the rvalue returned by the function. The compiler also generates the correct call to the destructor of the derived class, regardless of whether the destructor in the base class is virtual or not. This is because the type of the temporary object created is based on the type of the expression being assigned, and not on the type of link initialization.
Note that the question of how many copies of the return value is made is completely separate from optimizing the return value and optimizing the named return value. These optimizations relate to eliminating a copy of either the rvalue result of evaluating the returned expression, or the named local variable in the return value of the function in the body of the function itself. Obviously, in the best possible case, it is possible to optimize both the optimization of the return value and the temporary value of the return value, which can be eliminated, which will not lead to copies on the returned object.
Charles Bailey
source share