Abc &obj11 = fun1();
This line makes the program ill-formed; the C++ specification forbids temporaries to be bound to a reference that is not const
. A compliant C++ compiler would emit an error to this effect. Presumably you are using the Microsoft Visual C++ compiler, which is well-known for allowing the binding of a temporary to a non-const
reference in contradiction to the C++ specification.
const Abc &obj11 = fun1();
This line would be well-formed, and it causes the temporary to be bound to the reference.
In any case, when binding a temporary to a reference the temporary will have its lifetime extended to match the lifetime of the reference, so when the reference goes out of scope the temporary will also be destroyed. In other words, in terms of lifetime semantics it’s equivalent to the line Abc obj1 = fun1();
1. If you are using a compiler that elides copies then all copies will be elided in both cases. If not eliding copies then the reference case will involve one less copy:
- Value case, the returned object will be copied into a temporary and then destroyed, and the temporary will be copied into
obj1
and then destroyed. - Reference case, the returned object will be copied into a temporary and then destroyed, and the temporary will be bound to the reference.
Note that a decent optimizing compiler will optimize away all copies as well as the reference detail completely, leaving you with identical assembly output for both of the cases in your question.
(If you’re interested, here is a test case with code slightly tweaked from that in your question. Note that no copies are made in either case unless copy elision is disabled.)
1 Note that this is different from the code Abc obj1; obj1 = fun1();
in your question. I intentionally changed it, because the code you have written isn’t directly comparable and so it doesn’t make much sense to compare them. If you rewrite it as Abc obj1 = fun1();
then the two lines can be compared, because Abc obj1; obj1 = fun1();
involves default-construction and then copy-assignment.
9
solved What’s the difference between class reference and class object when the function return class object in C++?