Re: The best way to retrieve a returned value... by const reference?
"Niels Dekker - no reply address" <noreply@this.is.invalid>
Suppose you're calling a function that returns an object "by value". When
const access to the returned value is sufficient, you have the choice
between binding the returned object to a const-reference, and copying the
object to a local (const) variable, using copy-initialization:
class Foo { /* ... */ };
Foo GetFoo(void);
const Foo& constReference = GetFoo(); // Choice #1
const Foo constValue = GetFoo(); // Choice #2
Personally, I have the habbit to bind such an object to a const-reference
(choice #1).
I too, often use that. Looking around the web it seems not a well-known
feature of C++ (that the life of bound object is extended to life of ref...)
but there are no other problems I'm aware of.
Thereby I hope to avoid an expensive copy-construction, which /might/ take
place when you use copy-initialization (choice #2). Is it a common
practice to do so?
So far I haven't been able to prove that choice #1 is really superior to
choice #2, though.
Note that the preferred form for that is not copy-init, but direct-init!
const Foo constValue(GetFoo());
Many optimizers can create identical code for all the three forms --
completely removing copies.
I tried both MSVC 2008 SP1 and GCC 4.3.2, and I couldn't find a
performance difference. It appears that both compilers do copy elision,
whenever using copy-initialization to retrieve the returned value (choice
#2).
Yeah.
But I'd rather not depend on a compiler version specific optimization.
(GCC actually allows switching off copy elision by
"-fno-elide-constructors".) What do you think? Do you have an example in
which one choice really outperforms the other?
Performance is not thing you speculate but one you measure with profiler.
Common observation is that bottlenecks are not at places programmers would
think...
Also they can move around depending on processor, cache, memory, etc.
IMO don't sweat it, inless you see some real point against using the ref
form, use that, it won't let you down. :)