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

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

概述考虑以下示例程序: #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. 考虑以下示例程序:
#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链接: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类型).

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

总结

以上是内存溢出为你收集整理的c – 以逗号分隔的表达式调用析构函数全部内容,希望文章能够帮你解决c – 以逗号分隔的表达式调用析构函数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1243071.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存