The best way to retrieve a returned value... by const reference?
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). 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. 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). 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?
Note that Igor Tandetnik and Alex Blekhman also gave me some useful
feedback at microsoft.public.vc.language, subject "Does binding to
const-reference outperform copy-initialization from returned value?", at
http://groups.google.com/group/microsoft.public.vc.language/browse_thread/thread/c009118b7057e547
Kind regards,
--
Niels Dekker
http://www.xs4all.nl/~nd/dekkerware
Scientific programmer at LKEB, Leiden University Medical Center