开发者

Why has the destructor been called only once?

#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;
}

the console output is :

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

construct ..

destruct...


Its because of copy-elision by the compiler when you return the value from the function. In this case, the copy-elision is called RVO - Return Value Optimization.

See these

  • Return Value Optimization
  • Copy elision


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

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.


Compiler optimizations.

On other compilers/optimization settings, it might get called more than once.

See this compile: http://codepad.org/8kiVC3MM

Output:
1 construct ..
2 destruct...
3 destruct...
4 destruct...
5 destruct...

Note that the defined constructor wasn't called all those times because the compiler-generated copy constructor was called instead.

See this compile: http://codepad.org/cx7tDVDV

... where I defined an extra copy constructor on top of your code:

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

Output:
1 construct ..
2 cctor
3 destruct...
4 cctor
5 destruct...
6 cctor
7 destruct...
8 destruct...


It's called return value optimization, or RVO.


Try g++ -fno-elide-constructors (and define a copy constructor that prints a message).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜