加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 04:54:41 所属栏目:百科 来源:网络整理
导读:考虑以下示例程序: #include iostreamusing namespace std;struct t{ ~t() {cout "destroyedn"; }};int main(){ cout "testn"; t(),cout "doing stuffn"; cout "endn";} 我从GCC 4.9.2获得的输出是: test doing stuff destroyed end cpp.sh链接:http:
考虑以下示例程序:
#include <iostream>
using namespace std;
struct t
{
    ~t() {cout << "destroyedn"; }
};
int main()
{
    cout << "testn";
    t(),cout << "doing stuffn";
    cout << "endn";
}

我从GCC 4.9.2获得的输出是:

test 
doing stuff 
destroyed 
end

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

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

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

我希望在cout<<之前调用~t() “做东西” 这是标准行为吗?如果是这样,它在标准中的定义是什么?

解决方法

“其结果被丢弃”意味着忽略子表达式的值(此处为t类型).

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读