gpt4 book ai didi

c++ - 逗号分隔语句中返回值的生命周期

转载 作者:搜寻专家 更新时间:2023-10-31 00:02:34 25 4
gpt4 key购买 nike

下面三行注释的执行顺序有保证吗?

struct S
{
S() { /* called 1st */ }
~S() { /* called 3rd */ }
};

boost::shared_ptr<S> f()
{
return boost::shared_ptr<S>(new S);
}

int second() { return 0; /* called 2nd */ }

int test()
{
return (f(), second());
}

在我的编译器中,f() 返回的 shared_ptr 似乎一直存在到调用 second() 之后。但这是由标准和其他编译器保证的吗?

最佳答案

临时对象一直存在到完整表达式完成。

[n3290: 12.2/3]: When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), 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 (12.4). 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. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.

和:

[n3290: 1.9/10]: A full-expression is an expression that is not a subexpression of another expression. If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. A call to a destructor generated at the end of the lifetime of an object other than a temporary object is an implicit full-expression. Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression. [..]

这意味着 f()second() 都应该存在,直到执行从 test() 返回评估结果后者。

关于c++ - 逗号分隔语句中返回值的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7820429/

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