析构函数调用逗号分隔的表达式

时间:2017-06-01 13:52:16

标签: c++ language-lawyer object-lifetime temporary-objects comma-operator

考虑以下示例程序:

#include <iostream>
using namespace std;
struct t
{
    ~t() {cout << "destroyed\n"; }
};
int main()
{
    cout << "test\n";
    t(), cout << "doing stuff\n";
    cout << "end\n";
}

我用GCC 4.9.2获得的输出是:

test 
doing stuff 
destroyed 
end

cpp.sh link:http://cpp.sh/3cvm

但是根据关于逗号运算符的cppreference:

  

在逗号表达式E1,E2中,评估表达式E1,丢弃其结果,并在评估表达式E2开始之前完成其副作用

我希望在~t()

之前调用cout << "doing stuff"

这是标准行为吗?如果是这样,它在标准中定义了什么?

2 个答案:

答案 0 :(得分:12)

&#34;其结果被丢弃&#34;表示忽略子表达式的(此处为t类型)。

然而,它的生命周期并未受到影响:正如任何临时表演一样,它在全表达结束时被破坏(即这里的分号)。

答案 1 :(得分:6)

这里的cppreference措辞是不幸的。

与任何临时版本一样,此版本将一直持续到 full-expression 的结尾。

通过“副作用”,它正在讨论临时的构造