Guaranteed lifetime of temporary in C++?

The destructor for that sort of temporaries is called at the end of the full-expression. That’s the most outer expression which is not part of any other expression. That is in your case after the function returns and the value is evaluated. So, it will work all nice.

It’s in fact what makes expression templates work: They can keep hold references to that sort of temporaries in an expression like

e = a + b * c / d

Because every temporary will last until the expression

x = y

Is evaluated completely. It’s quite concisely described in 12.2 Temporary objects in the Standard.

Leave a Comment