【问题标题】:Why has the destructor been called only once?为什么只调用了一次析构函数?
【发布时间】:2011-09-19 07:26:29
【问题描述】:
#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 

构造..

破坏...

【问题讨论】:

标签: c++ destructor


【解决方案1】:

这是因为当您从函数返回值时,编译器会进行复制省略。在这种情况下,复制省略称为 RVO - 返回值优化。

看看这些

【讨论】:

    【解决方案2】:

    编译器优化。

    在其他编译器/优化设置中,它可能会被多次调用。

    查看此编译:http://codepad.org/8kiVC3MM

    输出:
    1 构造..
    2 破坏...
    3 破坏...
    4 破坏...
    5 破坏...

    请注意,并非所有这些时间都调用定义的构造函数,因为调用的是编译器生成的复制构造函数。

    查看此编译:http://codepad.org/cx7tDVDV

    ...我在您的代码之上定义了一个额外的复制构造函数:

    Test(const Test& other)
    {
        printf("cctor\n");
    }
    

    输出:
    1 构造..
    2 cctor
    3 破坏...
    4 cctor
    5 破坏...
    6 cctor
    7 破坏...
    8破坏……

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

        这叫做返回值优化,或者RVO

        【讨论】:

          【解决方案5】:

          试试g++ -fno-elide-constructors(并定义一个打印消息的复制构造函数)。

          【讨论】:

            猜你喜欢
            • 2013-12-11
            • 2013-11-24
            • 2022-07-05
            • 1970-01-01
            • 2013-01-12
            • 1970-01-01
            • 2015-04-28
            • 1970-01-01
            相关资源
            最近更新 更多