Why has the destructor been called only once?

时间秒杀一切 提交于 2019-11-28 01:52:41

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.

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

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).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!