Lifetime of temporary within operator+ sequence [duplicate]
Possible Duplicate:
Guaranteed lifetime of temporary in C++? Lifetime of temporaries
I have a 开发者_开发百科quick question regarding the lifespan of a temporary object, when returned from an overloaded operator+
method. For example, if the expression...
a = b + c + d + e
...is evaluated by overloaded operator+
methods which return temporary objects, is the scope of the temporary returned by the sub-expression b + c
that of the entire expression?
As g++ appears to hold onto all temporaries whilst the entire expression is within scope, references to these values may be held for delayed evaluation during the a =
assignment.
Could somebody please confirm whether or not this behaviour is guaranteed for all C++ implementations?
Yes, in the usual case: "Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created." (§12.2/3).
There a couple of exceptions to this, but they don't apply here.
Yes, a temporary object is only destroyed after all evaluations in the full-expression. (A statement is the most common kind of full-expression. Certain uses of references can make a temporary object last longer.)
This may be a bit off topic, but there are differences between G++ (MinGW 4.4.1) and MSCV++ 10 in the scope of returned temporary variables created on the stack.
I just created an object, called say myObj and class members are coordinates, vectors, whatever ...
The class has a default constructor, another constructor that initializes class members, a copy constructor, and overloaded +, += and = operators.
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;
}
The + operator allocates a myObj object on the stack (NOT using new) and adds the objects *this and mO (via retO) and assigns them to the retO object created on the stack.
G++ allows you to call:
myObj2 = myObj1 + myObj2;
However, Visual Studio 10.0 destroys retO that was created on the stack immediately after the overloaded operator member function exits (verified using static member increment and decrement with output inside all constructors and the destructor).
I do not know how the standard defines this behavior. Oddly enough, MinGW gives a compiler warning whereas MSVC++ 10 does not.
Of course the problem with creating a new myObj object with the new keyword is memory leakage as the above construct does not keep a reference to the new myObj instantiation, which is allocated to myObj2.
Regards,
Navid
精彩评论