When are temporaries created as part of a function call destroyed?

后端 未结 4 1088
-上瘾入骨i
-上瘾入骨i 2021-01-01 13:14

Is a temporary created as part of an argument to a function call guaranteed to stay around until the called function ends, even if the temporary isn\'t passed directly to th

4条回答
  •  粉色の甜心
    2021-01-01 13:42

    Temporary objects exist up until the end of the full expression in which they are created.

    In your example, the A object created by A(4) will exist at least until the expression ends just after the return from the call to foo().

    This behavior is guaranteed by the language standard:

    Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception (C++03 §12.2/3).

    The lifetime of the temporary may be extended by binding a reference to it (in which case its lifetime is extended until the end of the lifetime of the reference), or by using it as an initializer in a constructor's initializer list (in which case its lifetime is extended until the object being constructed is fully constructed).

提交回复
热议问题