加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 从“T :: operator(const T&rhs)const”返回“const T

发布时间:2020-12-16 09:54:51 所属栏目:百科 来源:网络整理
导读:我经常看到我的老师使用const运算符 – * /返回const值.这样做是一种好习惯吗?我应该为我写的每个班级都这样做吗? (T表示任何重载运算符的结构/类 – * /). 例如: struct Fraction{ //something here. const Fraction operator+(const Fraction rhs) cons
我经常看到我的老师使用const运算符 – * /返回const值.这样做是一种好习惯吗?我应该为我写的每个班级都这样做吗? (T表示任何重载运算符的结构/类 – * /).

例如:

struct Fraction
{
    //something here.
    const Fraction operator+(const Fraction &rhs) const;
    const Fraction operator-(const Fraction &rhs) const;
    const Fraction operator*(const Fraction &rhs) const;
    const Fraction operator/(const Fraction &rhs) const;
};

解决方法

不,这是一个坏主意,因为它抑制了移动语义.在下面的:

a = b + c;

b c的临时结果可以移动到if不是const,但如果是const则必须复制.复制通常比移动更昂贵.

从历史上看,在移动语义之前的几天,有人建议防止像(a b)= c这样的无意义.一些人认为最好使其导致编译时错误,而不是奇怪的运行时行为.如今,即使您同意这一论点,这样做也需要付出代价.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读