返回值优化(RVO)

C++的函数中,如果返回值是一个对象,那么理论上它不可避免的会调用对象的构造函数和析构函数,从而导致一定的效率损耗。如下函数所示:

A test()
{
    A a;
    return a;
}

在test函数里,生成了一个A的临时对象,之后将它作为返回值返回,在生成a的过程中会调用constructor,离开函数的时候会调用该临时对象的destructor。

C++的编译器采用了一种称为返回值优化(RVO)的技术,假设说这么写代码:

A test()
{
    return A();
}
A a=test();

编译器会将test函数里A的构造过程直接运用在a上,从而你只需要付出一个constructor的代价,节省了构造临时对象的代价。

最后是一个例子,测试环境为VS2010:

class A
{
public:
    A()
    {
        std::cout<<"A constructor"<<std::endl;
    }
    ~A()
    {
        std::cout<<"A destructor"<<std::endl;
    }
};
A test1()
{
    return A();
}

A test2()
{
    A a;
    return a;
}

int main()
{
    A a1=test1();
    A a2=test2();
    system("pause");
    return 0;
}

test2在函数中构造了临时对象并返回,test1则直接在return语句处构造对象,输出结果如下:

A constructor
A constructor
A destructor

可以看到,编译器在此处使用了RVO,提高了程序的效率。

原文地址:https://www.cnblogs.com/wickedpriest/p/5684115.html