必須返回對象時,別妄想返回其reference 【Effective C++ 條款21】

  • 2020 年 5 月 20 日
  • 筆記
class Rational
{
public:
    Rational(int numerator = 0, int denominator = 1) : n(numerator), d(denominator) {
        printf("Rational Constructor\n");
    }
    ~Rational() {
        printf("Rational Destructor\n");
    }
    Rational(const Rational& rhs) {
        this->d = rhs.d;
        this->n = rhs.n;
        printf("Rational Copy Constructor\n");
    }
private:
    int n, d;
    friend const Rational operator*(const Rational& lhs, const Rational& rhs);
};

Rational的*運算符可以這樣重載:

const Rational operator*(const Rational& lhs, const Rational& rhs)
{
    Rational tmp(lhs.n * rhs.n, lhs.d * rhs.d);
    return tmp;
}

但是不可以這樣重載:【區別在於一個&】

const Rational& operator*(const Rational& lhs, const Rational& rhs)
{
    Rational tmp(lhs.n * rhs.n, lhs.d * rhs.d);
    return tmp;
}

當這樣去使用:

Rational x(1, 2), y(2, 3);
Rational z = x * y;

第一種方法可以得到正確的結果,因為會調用Rational的拷貝構造函數將tmp賦給z,但是第二種方法返回的是tmp的引用,在函數退出前,tmp就被銷毀了,所以這樣做是不對的。

不過,第一種方法雖然功能上沒有問題,但是效率上有所欠缺,因為調用了三次構造函數,一次複製構造函數,一次析構函數

Rational Constructor
Rational Constructor
Rational Constructor
Rational Copy Constructor
Rational Destructor

可以進行返回值優化如下:

const Rational operator*(const Rational& lhs, const Rational& rhs)
{
    return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}
Rational Constructor
Rational Constructor
Rational Constructor

優化之後少調用了一次複製構造函數和析構函數

完整程式碼如下:

#include <stdio.h>
class Rational
{
public:
    Rational(int numerator = 0, int denominator = 1) : n(numerator), d(denominator) {
        printf("Rational Constructor\n");
    }
    ~Rational() {
        printf("Rational Destructor\n");
    }
    Rational(const Rational& rhs) {
        this->d = rhs.d;
        this->n = rhs.n;
        printf("Rational Copy Constructor\n");
    }
private:
    int n, d;
    friend const Rational operator*(const Rational& lhs, const Rational& rhs);
};

const Rational operator*(const Rational& lhs, const Rational& rhs)
{
    return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

int main()
{
    Rational x(1, 2), y(2, 3);
    Rational z = x * y;
    return 0;
}