为什么析构函数只被调用一次?
#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
构造..
破坏...
#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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是因为当您从函数返回值时,编译器会进行复制省略。在这种情况下,复制省略称为 RVO - 返回值优化。
请参阅这些
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
我想原因是“Get”中的返回值优化。
看看 http://en.wikipedia.org/wiki/Return_value_optimization
实际上你的代码是不是标准示例,但也许您的编译器也在这里应用它。
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.
编译器优化。
在其他编译器/优化设置上,它可能会被多次调用。
请参阅此编译:http://codepad.org/8kiVC3MM
请注意,定义的构造函数并没有一直被调用,因为而是调用了编译器生成的复制构造函数。
请参阅此编译: http://codepad.org/cx7tDVDV
...我在顶部定义了一个额外的复制构造函数你的代码:
Compiler optimizations.
On other compilers/optimization settings, it might get called more than once.
See this compile: http://codepad.org/8kiVC3MM
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:
这称为返回值优化,或RVO。
It's called return value optimization, or RVO.
尝试
g++ -fno-elide-constructors
(并定义一个打印消息的复制构造函数)。Try
g++ -fno-elide-constructors
(and define a copy constructor that prints a message).