C++中的返回值優(yōu)化
原文出自程序人生 >> C++中的返回值優(yōu)化(return value optimization)返回值優(yōu)化(Return Value Optimization,簡稱RVO),是這么一種優(yōu)化機制:當(dāng)函數(shù)需要返回一個對象的時候,如果自己創(chuàng)建一個臨時對象用戶返回,那么這個臨時對象會消耗一個構(gòu)造函數(shù)(Constructor)的調(diào)用、一個復(fù)制構(gòu)造函數(shù)的調(diào)用(Copy Constructor)以及一個析構(gòu)函數(shù)(Destructor)的調(diào)用的代價。而如果稍微做一點優(yōu)化,就可以將成本降低到一個構(gòu)造函數(shù)的代價,下面是在Visual Studio 2008的Debug模式下做的一個測試:(在GCC下測試的時候可能編譯器自己進行了RVO優(yōu)化,看不到兩種代碼的區(qū)別)
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òu)造函數(shù)(Constructor)的調(diào)用、一個復(fù)制構(gòu)造函數(shù)的調(diào)用(Copy Constructor)以及一個析構(gòu)函數(shù)(Destructor)的調(diào)用的代價。
而如果把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()); } |
原創(chuàng)文章,轉(zhuǎn)載請注明:
本文出自程序人生 >> C++中的返回值優(yōu)化(return value optimization)
作者:代碼瘋子
posted on 2011-10-12 18:40 LoveBeyond 閱讀(3384) 評論(7) 編輯 收藏 引用