LoveBeyond

C++中的返回值优化

原文出自程序人生 >> C++中的返回值优化(return value optimization)
返回值优化(Return Value Optimization,简称RVO),是这么一种优化机制:当函数需要返回一个对象的时候,如果自己创建一个临时对象用户返回,那么这个临时对象会消耗一个构造函数(Constructor)的调用、一个复制构造函数的调用(Copy Constructor)以及一个析构函数(Destructor)的调用的代价。而如果稍微做一点优化,就可以将成本降低到一个构造函数的代价,下面是在Visual Studio 2008的Debug模式下做的一个测试:(在GCC下测试的时候可能编译器自己进行了RVO优化,看不到两种代码的区别)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// C++ Return Value Optimization
// 作者:代码疯子
// 博客:http://www.programlife.net/
#include <iostream>
using namespace std;
 
class Rational
{
public:
	Rational(int numerator = 0, int denominator = 1) : 
	  n(numerator), d(denominator)
	  {
		  cout << "Constructor Called..." << endl;
	  }
	  ~Rational()
	  {
		  cout << "Destructor Called..." << endl;
	  }
	  Rational(const Rational& rhs)
	  {
		  this->d = rhs.d;
		  this->n = rhs.n;
		  cout << "Copy Constructor Called..." << endl;
	  }
	  int numerator() const { return n; }
	  int denominator() const { return d; }
private:
	int n, d;
};
 
//const Rational operator*(const Rational& lhs,
//						 const Rational& rhs)
//{
//	return Rational(lhs.numerator() * rhs.numerator(),
//					lhs.denominator() * rhs.denominator());
//}
 
const Rational operator*(const Rational& lhs,
						 const Rational& rhs)
{
	cout << "----------- Enter operator* -----------" << endl;
	Rational tmp(lhs.numerator() * rhs.numerator(),
		lhs.denominator() * rhs.denominator());
	cout << "----------- Leave operator* -----------" << endl;
	return tmp;
}
 
int main(int argc, char **argv)
{
	Rational x(1, 5), y(2, 9);
	Rational z = x * y;
	cout << "calc result: " << z.numerator() 
		<< "/" << z.denominator() << endl;
 
	return 0;
}

函数输出截图如下:
Return Value Optimization
可以看到消耗一个构造函数(Constructor)的调用、一个复制构造函数的调用(Copy Constructor)以及一个析构函数(Destructor)的调用的代价。

而如果把operator*换成另一种形式:

1
2
3
4
5
6
const Rational operator*(const Rational& lhs,
				const Rational& rhs)
{
	return Rational(lhs.numerator() * rhs.numerator(),
				lhs.denominator() * rhs.denominator());
}

就只会消耗一个构造函数的成本了:
返回值优化

原创文章,转载请注明:
本文出自程序人生 >> C++中的返回值优化(return value optimization)
作者:代码疯子

您可能对下面的文章也感兴趣:
  1. 空白基类最优化 The Empty Base Class Optimization (EBCO) (13.2)
  2. 又是C++空类 (10)
  3. 在构造函数抛出异常后析构函数将不再被调用 (9.2)
  4. Rational Rose 2003下载地址 (8.6)
  5. 阻止编译器自动生成copy函数 (6.4)
分类:C++编程标签:

posted on 2011-10-12 18:40 LoveBeyond 阅读(3334) 评论(7)  编辑 收藏 引用

<2011年10月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

留言簿(1)

文章分类

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜

友情链接:C++博客 LoveBeyond 代码疯子 程序人生 C++技术博客