Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1448008
  • 博文数量: 150
  • 博客积分: 65
  • 博客等级: 民兵
  • 技术积分: 3415
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-25 10:30
个人简介

游戏后台开发

文章分类

全部博文(150)

文章存档

2020年(1)

2019年(4)

2017年(3)

2016年(6)

2015年(4)

2014年(45)

2013年(86)

2012年(1)

分类: C/C++

2014-01-13 01:34:32

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

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。

阅读(2103) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~