为什么析构函数只被调用一次? [英] Why has the destructor been called only once?

查看:171
本文介绍了为什么析构函数只被调用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 

建构..

destruct ...

destruct...

推荐答案

我想原因是在Get中返回值优化。

I suppose the reason is return value optimization in 'Get'.

a href =http://en.wikipedia.org/wiki/Return_value_optimization =nofollow> http://en.wikipedia.org/wiki/Return_value_optimization

Have a look at http://en.wikipedia.org/wiki/Return_value_optimization

实际上,你的代码不是标准的例子,但也许你的编译器也在这里应用它。

Actually your code is not the standard example, but maybe your compiler applies it here as well.

这篇关于为什么析构函数只被调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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