The lifetime of the time inside the operator + sequence

Possible duplicate:
Guaranteed lifetime in C ++? Life time in time

I have a quick question regarding the lifespan of a temporary object when it returns from an overloaded method operator+. For example, if the expression ...

a = b + c + d + e

... evaluated by overloaded methods operator+that return temporary objects, is the scope of the temporary expression returned by the sub-expression the b + cwhole expression?

Since g ++ seems to hold all the time sections while the entire expression is within scope, references to these values ​​can be held for deferred evaluation at the time of assignment a =.

Can anyone confirm if this behavior is guaranteed for all C ++ implementations?

+5
source share
3 answers

Yes, in the usual case: “Temporary objects are destroyed as the last step in evaluating the full expression (1.9), which (lexically) contains the point at which they were created” (§12.2 / 3).

There are a few exceptions to this, but they do not apply here.

+6
source

Yes, a temporary object is destroyed only after all evaluations in full terms. (A statement is the most common type of full expression. Some reference applications can make a temporary object longer.)

+1
source

, g++ (MinGW 4.4.1) MSCV ++ 10 , .

, myObj, - , , ...

, , , +, + = = .

myObj & myObj::operator+(myObj & mO)
{
    myObj retO = myObj(mO); // using a non-default constructor defined
    retO += *this;          // Uses the other overloaded operator defined.
    return retO;
}

+ myObj ( ) * this mO ( retO) retO, .

g++ :

myObj2 = myObj1 + myObj2;

Visual Studio 10.0 retO, , - ( ).

, . , MinGW , MSV++ 10 .

Of course, the problem with creating a new myObj object with a new keyword is a memory leak, because the above construction does not support a link to a new instance of myObj that is allocated by myObj2.

Hi,

By the look

0
source

All Articles