根据documentation(),其中说:
当实现引入类的临时对象时, 具有非平凡的构造函数([class.default.ctor], [class.copy.ctor]),则应确保需要构造函数 临时对象。同样,析构函数应被要求 具有非平凡析构函数的临时变量([class.dtor])。临时 销毁物件是评估物件的最后一步 完全表达([intro.execution])包含(按词法) 指出它们的创建位置。即使那个评估也是如此 最后引发异常。价值计算和副作用 销毁临时对象的过程仅与 完整表达式,不包含任何特定的子表达式。
如何理解“临时对象被销毁是评估(在词法上)包含创建对象的完整表达式([intro.execution])的最后一步。”现在是否可以通过一些简单的示例来使它清楚?
简单的例子。此表达式产生一个临时对象:
在这里,该表达式用作子表达式:
在点A,临时对象已被破坏,因为该点位于创建临时对象的完整表达式之后。
An explanation that works in many cases is that temporary objects are destroyed when execution reaches the semicolon at the end of the statement. Some language constructs (such as a
for
loop) are not covered by this explanation, so don't push it too hard.