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;
} |
函數(shù)輸出截圖如下:

可以看到消耗一個(gè)構(gòu)造函數(shù)(Constructor)的調(diào)用、一個(gè)復(fù)制構(gòu)造函數(shù)的調(diào)用(Copy Constructor)以及一個(gè)析構(gòu)函數(shù)(Destructor)的調(diào)用的代價(jià)。
而如果把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());
} |
就只會(huì)消耗一個(gè)構(gòu)造函數(shù)的成本了:

原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明:
本文出自程序人生 >> C++中的返回值優(yōu)化(return value optimization)
作者:代碼瘋子
您可能對(duì)下面的文章也感興趣:
- 空白基類最優(yōu)化 The Empty Base Class Optimization (EBCO) (13.2)
- 又是C++空類 (10)
- 在構(gòu)造函數(shù)拋出異常后析構(gòu)函數(shù)將不再被調(diào)用 (9.2)
- Rational Rose 2003下載地址 (8.6)
- 阻止編譯器自動(dòng)生成copy函數(shù) (6.4)