ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

必须返回对象时,别妄想返回其reference 【Effective C++ 条款21】

2020-05-20 19:54:48  阅读:271  来源: 互联网

标签:返回 const Effective reference int rhs lhs Rational Constructor


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;
}

 

标签:返回,const,Effective,reference,int,rhs,lhs,Rational,Constructor
来源: https://www.cnblogs.com/nidhogh/p/12925693.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有