Re: The best way to retrieve a returned value... by const reference?
Thanks to all of you for your replies so far!
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).
Pete Becker wrote:
I don't think that this avoids the copy. The returned value has to
live somewhere in the current stack frame, so it has to be copied
into a temporary object, where "copied" means the same things as in
#2.
When I use the option "-fno-elide-constructors" on GCC 4.3.2, choice #1
/does/ avoid a copy. The following example gets me two copy-constructor
calls for the initialization of constValue, and just one for constReference:
//////////////////////////////////////////////////
class Foo
{
public:
unsigned copyCount;
Foo(void)
:
copyCount(0)
{
}
Foo(const Foo& arg)
:
copyCount(arg.copyCount + 1)
{
}
Foo& operator=(const Foo& arg)
{
copyCount = arg.copyCount + 1;
return *this;
}
};
Foo GetFoo(void)
{
return Foo();
}
int main(void)
{
const Foo& constReference = GetFoo();
const Foo constValue = GetFoo();
// Returns 9 when doing "gcc-4 -fno-elide-constructors"
return constReference.copyCount +
(constValue.copyCount << 2);
}
/////////////////////////////////////////////////
So when using "-fno-elide-constructors", binding to const-reference appears
superior. But honestly, I don't think I would ever switch on this option
for production code... So I'm still hoping to find a more realistic
scenario in which binding to const-reference would outperform
copy-initialization. Otherwise maybe I should change my habit!
Kind regards, Niels