编译器优化技术
现代编译器缺省会使用 RVO(return value optimization,返回值优化)、NRVO(named return value optimization、命名返回值优化)和复制省略(Copy elision)技术,来减少拷贝次数来提升代码的运行效率。
注1:vc6、vs 没有提供编译选项来关闭该优化,无论是 debug 还是 release 都会进行 RVO 和复制省略优化
注2:vc6、vs2005 以下及 vs2005 + Debug 上不支持 NRVO 优化,vs2005 + Release 支持 NRVO 优化
注3:g++ 支持这三种优化,并且可通过编译选项:-fno-elide-constructors
来关闭优化。
RVO 优化
如下程序:
#include <stdio.h>
class A
{
public:
A()
{
printf("%p construct\n", this);
}
A(const A& cp)
{
printf("%p copy construct\n", this);
}
~A()
{
printf("%p destruct\n", this);
}
};
A GetA()
{
return A();
}
int main()
{
{
A