每天早晨叫醒你的不是闹钟,而是梦想

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  62 Posts :: 0 Stories :: 5 Comments :: 0 Trackbacks

常用链接

留言簿(1)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

原文出自程序人生 >> C++中的返回值优化(return value optimization)
返回值优化(Return Value Optimization,简称RVO),是这么一种优化机制:当函数需要返回一个对象的时候,如果自己创建一个临时对象用户返回,那么这个临时对象会消耗一个构造函数(Constructor)的调用、一个复制构造函数的调用(Copy Constructor)以及一个析构函数(Destructor)的调用的代价。而如果稍微做一点优化,就可以将成本降低到一个构造函数的代价,下面是在Visual Studio 2008的Debug模式下做的一个测试:(在GCC下测试的时候可能编译器自己进行了RVO优化,看不到两种代码的区别)

 1 // C++ Return Value Optimization
 2 // 作者:代码疯子
 3 // 博客:http://www.programlife.net/
 4 #include <iostream>
 5 using namespace std;
 6  
 7 class Rational
 8 {
 9 public:
10     Rational(int numerator = 0, int denominator = 1) : 
11       n(numerator), d(denominator)
12       {
13           cout << "Constructor Called" << endl;
14       }
15       ~Rational()
16       {
17           cout << "Destructor Called" << endl;
18       }
19       Rational(const Rational& rhs)
20       {
21           this->d = rhs.d;
22           this->n = rhs.n;
23           cout << "Copy Constructor Called" << endl;
24       }
25       int numerator() const { return n; }
26       int denominator() const { return d; }
27 private:
28     int n, d;
29 };
30  
31 //const Rational operator*(const Rational& lhs,
32 //                         const Rational& rhs)
33 //{
34 //    return Rational(lhs.numerator() * rhs.numerator(),
35 //                    lhs.denominator() * rhs.denominator());
36 //}
37  
38 const Rational operator*(const Rational& lhs,
39                          const Rational& rhs)
40 {
41     cout << "----------- Enter operator* -----------" << endl;
42     Rational tmp(lhs.numerator() * rhs.numerator(),
43         lhs.denominator() * rhs.denominator());
44     cout << "----------- Leave operator* -----------" << endl;
45     return tmp;
46 }
47  
48 int main(int argc, char **argv)
49 {
50     Rational x(1, 5), y(2, 9);
51     Rational z = x * y;
52     cout << "calc result: " << z.numerator() 
53         << "/" << z.denominator() << endl;
54  
55     return 0;
56 }

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

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

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



就只会消耗一个构造函数的成本了:
返回值优化
posted on 2014-02-17 18:20 沛沛 阅读(263) 评论(0)  编辑 收藏 引用 所属分类: C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理