This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: g++ weird behavoir with values returned by copy.
- From: Nathan Sidwell <nathan at codesourcery dot com>
- To: Leandro Lucarella <llucar at mecon dot gov dot ar>
- Cc: gcc at gcc dot gnu dot org
- Date: Sun, 23 Nov 2003 15:58:17 +0000
- Subject: Re: g++ weird behavoir with values returned by copy.
- Organization: Codesourcery LLC
- References: <20031121230309.GA4629@mecon.gov.ar>
Leandro Lucarella wrote:
Is tmp who is returned, not a copy. This works fine on most cases, but
I've found a case where the behavoir is much more weird (at least for
me).
and I found a very weird case, in wich with cause an object to be
destroyed when it's still in use using a reference:
Not a bug. This is C++. The optimization you are observing is the
Return Value Optimization, and is not directly connected to the
effect you are seeing.
struct A {
A(void) {}
A(const A& a) {}
~A(void) {}
A& operator=(const A& a) {
return *this;
}
A& print(void) {
return *this;
}
};
A test(void) {
A tmp;
cout << "Doing something." << endl;
return tmp;
}
int main(void) {
A& ar = test().print();
// Now ar points to a destroyed objec
yes, as the std specified.
test () returns a temporary object, which is used in the call to A::print.
that returns a reference to self, which is bound to ar. As ar is not directly bound
to the temporary A that test returned, that is destroyed at the end of that full
expression.
you need to write
A &ar = test ();
ar.print ();
now, ar is directly bound to a temporary, and that temporary's lifetime is
extended to be the same as the reference to which it is bound.
nathan
--
Nathan Sidwell :: http://www.codesourcery.com :: CodeSourcery LLC
The voices in my head said this was stupid too
nathan@codesourcery.com :: http://www.planetfall.pwp.blueyonder.co.uk