返回值优化,RVO

2260阅读 0评论2014-01-13 chaohona
分类:C/C++

返回值优化,是一种属于编译器的技术,它通过转换源代码和对象的创建来加快源代码的执行速度。

RVO = return value optimization。

 

复制代码
class Complex//复数 {
    friendd Complex operator + (const Complex & , const Complex&); public:
    Conplex(double r=0.0,double i= 0.0): real(r),imag(i){}
    Complex(const Complex& a):real(a.real),imag(a.imag){};
    Complex operator = (const Complex &a); ~Complex(); private: double real; double imag;
};
复制代码

 

 对于执行 A=B+C;

的时候,编译器在原函数创建一个临时变量,作为第三个参数传给 operator +(),使用引用传递,然后再将值赋给 A。

 

很多的编译器都实现了这样的优化,不过在程序编写的时候需要注意某些细节,才能让编译器执行这一技术。如:

复制代码
//不能使用RVO Complex operator +(const Complex & a, const Complex &b)
{
    Complex retVal;
    retVal.real=a.real +b.real;
    retVal.imag=a.imag +b.imag; 
    return retVal;
} 
//能够使用RVO Complex operator +(const Complex & a, const Complex &b)
{ 
    double r=a.real +b.real; 
    double i=a.imag +b.imag; 
    return Complex(r,i);
}
复制代码

 

复制代码
//不能使用RVO Complex operator +(const Complex & a, const Complex &b)
{
    Complex C(a.real +b.real,a.imag +b.imag); 
    return C;
} 
//能够使用RVO Complex operator +(const Complex & a, const Complex &b)
{ 
    return C(a.real +b.real,a.imag +b.imag);
}
复制代码

 

 

另外,必须定义拷贝构造函数来“打开”RVO

 

另外还有一种是通过 够着函数实现的,称 计算性构造函数

复制代码
//计算性构造函数 Complex operator +(const Complex& a, const Complex &b)
{ 
    return Complex(a,b);
}

Complex::Complex(const Complex &a ,const Complex &b):real(a.real +b.real),imag(a.imag +b.imag){}
复制代码

 

 

 要点:

1.如果必须按值返回函数,通过RVO可以省去创建和销毁局部对象的步骤。

2.RVO 的应用要遵照编译器的实现而定。

3.通过编写计算性函数可以更好的使用RVO。

上一篇:TCP连接中的TIME_WAIT状态
下一篇:STL容器:vector