Are function return values automatic objects and thus guaranteed to be destructed?

Function return values are considered temporaries, and the construction of the return value is sequenced before the destruction of locals.

Unfortunately, this is underspecified in the standard. There is an open defect which describes this and offers some wording to fix the issue

[…] A return statement with an operand of type void shall be used only in a function whose return type is cv void. A return statement with any other operand shall be used only in a function whose return type is not cv void; the return statement initializes the object or reference to be returned by copy-initialization (8.5 [dcl.init]) from the operand. […]

The copy-initialization of the returned entity is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables (6.6 [stmt.jump]) of the block enclosing the return statement.

Since function return values are temporaries, they aren’t covered by the destructors are invoked for all automatic objects quote at the start of your post. However, [class.temporary]/3 says:

[…] Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. […]

So I think you could consider this a bug in GCC and Clang.

Don’t throw from destructors 😉

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)