0
点赞
收藏
分享

微信扫一扫

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


F.47: Return ​​T&​​ from assignment operators

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

Reason(原因)

The convention for operator overloads (especially on value types) is for​​operator=(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(示例)

 

class Foo{ public:    ...    Foo& operator=(const Foo& rhs) {      // Copy members.      ...      return *this;    }};

Enforcement(实施建议)

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

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

 

 


阅读更多更新文章,请关注微信公众号【面向对象思考】

举报

相关推荐

0 条评论