gpt4 book ai didi

c++ - 如何理解 “Temporary objs are destroyed as the last step in evaluating the full-expression”?有人可以通过一个简单的例子弄清楚吗?

转载 作者:行者123 更新时间:2023-12-02 09:53:56 31 4
gpt4 key购买 nike

根据documentation(),其中说:

When an implementation introduces a temporary object of a class that has a non-trivial constructor ([class.default.ctor], [class.copy.ctor]), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor ([class.dtor]). Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.



如何理解“临时对象被销毁是评估(从词法上)包含创建点的完整表达式([intro.execution])的最后一步。”今天是否可以通过一些简单的示例使它清楚?

最佳答案

简单的例子。此表达式产生一个临时对象:

std::string("test")

在这里,该表达式用作子表达式:
function(std::string("test"));
// point A

在点A,该临时对象已被破坏,因为该点位于创建临时对象的完整表达式之后。

如果无法理解此规则,这是如何编写错误的示例:
const std::string& function(const std::string& arg) {
return arg;
}

const std::string& ref = function("test");
std::cout << ref;

在这里,作为参数创建的临时对象在完整表达式后被销毁,因此 ref变为无效-悬挂的引用。当无效的引用插入到输出流中时,行为是不确定的。

关于c++ - 如何理解 “Temporary objs are destroyed as the last step in evaluating the full-expression”?有人可以通过一个简单的例子弄清楚吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61980083/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com