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 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



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