On 27 Mai, 18:37, Niels Dekker wrote:
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?
Common practice? I don't think so. In practise, there's only one
advantage of #1 over #2: The function can return some derived type
that you don't like to spell out which would be subject to slicing in
#2.
I can't speak for Microsoft's compiler but GCC elides the copy in #2
regardless of the optimization settings. It's a matter of the ABI and
how return-by-value is implemented. (GCC passes the address of the
future "constValue" to GetFoo and inside GetFoo the object is directly
constructed at the given address -- assuming (N)RVO is applicable).
True, it's an ABI issue. Sun Studio 12, for example, uses a trick
similar to that of gcc.