Let's say I have some function:
Foo GetFoo(..)
{
...
}
Assume that we neither know how this function is implemented nor the internals of Foo (it can be very complex object, for example). However we do know that function is returning Foo by value and that we want to use this return value as const.
Question: Would it be always a good idea to store return value of this function as const &
?
const Foo& f = GetFoo(...);
instead of,
const Foo f = GetFoo(...);
I know that compilers would do return value optimizations and may be move the object instead of copying it so in the end const &
might not have any advantages. However my question is, are there any disadvantages? Why shouldn't I just develop muscle memory to always use const &
to store return values given that I don't have to rely on compiler optimizations and the fact that even move operation can be expensive for complex objects.
Stretching this to extreme, why shouldn't I always use const &
for all variables that are immutable in my code? For example,
const int& a = 2;
const int& b = 2;
const int& c = c + d;
Besides being more verbose, are there any disadvantages?
question from:
https://stackoverflow.com/questions/37649236/why-not-always-assign-return-values-to-const-reference 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…