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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With