effective C++筆記之條款23:必須返回一個對象時不要試圖返回一個引用


l        想要返回一個對象的引用時,重載乘號操作符容易犯以下幾個錯誤,:

1        返回一個局部對象的引用

2        在堆上創建一個對象,然後返回它的引用,無法去delete它,造成內存泄漏

3        返回靜態對象的引用,導致兩個不同對象的==操作符總是爲真。

l        所以正確的乘法操作符應該返回一個新對象。這會導致operator的返回值構造和析構時帶來的開銷,但他只是用較小的代價換來正確的程序運行行爲而已。況且也有編譯器優化。

如下所示正確的重載乘號操作符:

class Rational

{

public:

        Rational(int num , int deno ) : n(num), d(deno)

        {

            cout<< "Rational(int ,int)"<< endl;

        }

        Rational(const Rational& other) : n(other.n), d(other.d)

        {

            cout<< "Rational(const Rational&)"<< endl;

        }

        Rational&operator=(constRational& other)

        {

            cout<< "operator =" << endl;

            n = other.n;

            d = other.d;

        }

        ~Rational()

        {

            cout<< "~Rational()" << endl;

        }

private:

        int n, d;

        friend const Rational operator*(const Rational& lhs, const Rational& rhs);

};

const Rationaloperator*(constRational& lhs,const Rational& rhs)

{

          return Rational(lhs.n * rhs.n, lhs.d * rhs.d);

}

//在有些場合,operator*的返回值會被安全地去除。

當在main中調用乘法操作符時,只會打印出現一個臨時對象構造與析構函數的調用,但應該創建出兩個臨時對象。

l        當需要在返回引用和返回對象間作決定時,你的職責是選擇可以完成正確功能的那個。至於怎麼讓這個選擇所產生的代價儘可能小,那是編譯器的生產商去想的事。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章