您的位置:首页 > 编程语言 > C语言/C++

c/c++:efficient c++,返回值优化,RVO

2015-09-24 21:48 399 查看
连接:/article/7144900.html

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

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: