前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.47 赋值运算符应该返回T&

C++核心准则编译边学-F.47 赋值运算符应该返回T&

作者头像
面向对象思考
发布2020-03-25 15:36:52
3270
发布2020-03-25 15:36:52
举报

F.47: Return T& from assignment operators

F.47 赋值运算符应该返回T&。

Reason(原因)

The convention for operator overloads (especially on value types) is foroperator=(const T&) to perform the assignment and then return (non-const)*this. This ensures consistency with standard-library types and follows the principle of "do as the ints do."

运算符重载的习惯(特别是值类型)是在operator=(const T&)中执行赋值操作然后返回(非常量)*this。这保证了和标准库类型的一致性而且遵守了“像整数一样动作”的准则。

译者注:“像整数一样动作”应该说的是,使用重载的赋值运算符的代码,看起来要和使用整数赋值运算符的代码具有同样的形式。

Note(注意)

Historically there was some guidance to make the assignment operator return const T&. This was primarily to avoid code of the form (a = b) = c -- such code is not common enough to warrant violating consistency with standard types.

历史上存在过某些保证赋值操作会返回const T&的准则。其主要目的是避免(a=b)=c--形式的代码,但这种代码的普遍性还不足以将其视为和对标准类型一致性的违反。

Example(示例)

代码语言:javascript
复制
class Foo
{
 public:
    ...
    Foo& operator=(const Foo& rhs) {
      // Copy members.
      ...
      return *this;
    }
};
代码语言:javascript
复制
Enforcement(实施建议)

This should be enforced by tooling by checking the return type (and return value) of any assignment operator.

应该强制对任何赋值运算符的返回值类型(和返回值)进行工具化检查。

觉得本文有帮助?请分享给更多人。

关注【面向对象思考】,轻松学习每一天!

有任何疑问,欢迎留言提问或讨论。


面向对象设计,面向对象编程,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.47: Return T& from assignment operators
    • Reason(原因)
      • Note(注意)
        • Example(示例)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档