Guaranteed lifetime of temporary in C++?

后端 未结 5 2019
天涯浪人
天涯浪人 2020-11-22 12:22

Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter? Here\'s an example class:

5条回答
  •  无人及你
    2020-11-22 12:46

    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.

提交回复
热议问题