Why do un-named C++ objects destruct before the scope block ends?

A temporary variable lives until the end of the full expression it was created in. Yours ends at the semicolon.

This is in 12.2/3:

Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

Your behavior is guaranteed.

There are two conditions that, if met, will extend the lifetime of a temporary. The first is when it’s an initializer for an object. The second is when a reference binds to a temporary.

Leave a Comment