用逗号分隔的表达式中的析构函数调用 [英] Destructor call in a comma-separated expression

查看:92
本文介绍了用逗号分隔的表达式中的析构函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例程序:

#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中获得的输出是:

The output I get with GCC 4.9.2 is:

test 
doing stuff 
destroyed 
end

cpp.sh链接: http://cpp.sh/3cvm

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

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

However according to cppreference about the comma operator:

在逗号表达式E1,E2中,对表达式E1进行求值,将其结果丢弃,并在开始对表达式E2求值之前完成其副作用

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins

我希望~t()cout << "doing stuff"

这是标准行为吗?如果是这样,那么该标准在哪里定义?

Is this a standard behavior? If so, where is it defined in the standard?

推荐答案

其结果被丢弃"表示子表达式的 value (此处为t类型)将被忽略.

"Its result is discarded" means that the subexpression's value (here of type t) is ignored.

但是,它的生命周期不受影响:与所有临时变量一样,它在完整表达式(即此处的分号)结束时被破坏.

Its lifetime, however, is unaffected: as any all temporaries, it is destructed at the end of the full-expression (i.e. the semicolon here).

这篇关于用逗号分隔的表达式中的析构函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆