[cfe-dev] interesting c++ puzzle

Jordan Rose jordan_rose at apple.com
Wed Jan 16 13:21:58 PST 2013

On Jan 16, 2013, at 13:12 , Krzysztof Parzyszek <kparzysz at codeaurora.org> wrote:

> On 1/16/2013 3:04 PM, reed kotler wrote:
>> This seems illogical to me. It does not call the copy constructor in
>> 5.cpp but in 6.cpp it tails
>> to compile because it can't find a valid copy constructor.
> IIRC, according to the standard, this
>  B b = f(1);
> is equivalent to
>  B b(f(1));
> I suppose the compiler refuses to treat f(1) as an object of type B&, since it's a temporary.  Again, if I remember things correctly...

Right, the standard requires that the copy constructor exist, but allows the copy itself to be elided. In C++11, a move constructor would work here as well.

C++11 [class.temporary]p1: Temporaries of class type are created in various contexts: ...returning a prvalue (6.6.3)…

C++11 [class.copy]p31: When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object...in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv- unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value, [and] when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20130116/d1c0ffc6/attachment.html>

More information about the cfe-dev mailing list