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

c – 为什么析构函数只被调用一次?

发布时间:2020-12-16 03:13:26 所属栏目:百科 来源:网络整理
导读:#include iostreamusing namespace std;class Test{public: Test() { printf("construct ..n"); } ~Test() { printf("destruct...n"); } };Test Get(){ Test t = Test(); return t;}int main(int argc,char *argv[]){ Test t = Get(); return 0;} 控制台的
#include <iostream>

using namespace std;

class Test
{
public:
    Test()
    {   
        printf("construct ..n");
    }   

    ~Test()
    {   
        printf("destruct...n");
    }   
};

Test Get()
{
    Test t = Test();
    return t;
}

int main(int argc,char *argv[])
{
    Test t = Get();
    return 0;
}

控制台的输出是:

$g++ -g -Wall -O0 testdestructor.cc
$./a.out

构造..

破坏…

解决方法

我认为原因是在’Get’中返回值优化.

看看http://en.wikipedia.org/wiki/Return_value_optimization

其实您的代码不是标准示例,但也可能您的编译器也适用于此.

(编辑:李大同)

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

    推荐文章
      热点阅读