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

标签 c++ shared-ptr comma-operator

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

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/

相关文章:

c++ - Visual Studio 2017 在 extern "C"中使用模板时出现不正确的错误

c++ - 使用 libtool 链接非 libtool 库

c++ - 如何修复 "Invalid read of size 8 - 40 bytes inside a block of size 64 free' d"

c++ - 为什么 std::shared_ptr 不接受我的删除函数对象?

c++ - 这个动态分配有什么作用?

C++ CRTP派生类对象切片

Java 运行时性能与 native C/C++ 代码的比较?

c++ - 如何在 C++/STL 中表示键值树

JavaScript 逗号运算符

c++ - 逗号运算符的局限性