Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of temporary within operator+ sequence [duplicate]

Tags:

c++

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?

like image 368
Taliadon Avatar asked Jul 10 '11 03:07

Taliadon


2 Answers

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.

like image 57
Jerry Coffin Avatar answered Oct 12 '22 08:10

Jerry Coffin


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

like image 39
aschepler Avatar answered Oct 12 '22 09:10

aschepler