This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: g++ weird behavoir with values returned by copy.


[Leandro Lucarella]
> I found that it doesn't return a copy, at least when I'm returning
> a local variable created in my function (or method).

Quoth the Standard, 

12.8.15:
"For a function with a class return type, if the expression in the return
statement is the name of a local object, and the cv-unqualified type of the
local object is the same as the function return type, an implementation is
permitted to omit creating the temporary object to hold the function return
value, even if the class copy constructor or destructor has side effects. In
these cases, the object is destroyed at the later of times when the original
and the copy would have been destroyed without the optimization.... Because
only one object is destroyed instead of two, and one copy constructor is not
executed, there is still one object destroyed for each one constructed."

This is the return value optimization.  g++ conforms to the Standard here.

> A& ar = test().print();

This is just plain wrong regardless of the presence of the return value
optimization.  Don't bind references to temporary objects.

(In general, reference members and reference local variables are evil.
Don't use them.)

> I don't know if this behavoir is normal since I'm a relative newbie C++
> programmer, but I found it odd so I thought it could be some kind of bug.

This is not g++'s fault.

C++ questions are not on topic for this list.  I suggest you pick up _C++
Primer Plus, Fourth Edition_ by Stephen Prata, or another book on modern
C++.

Stephan T. Lavavej
http://nuwen.net




Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]