T&
from assignment operatorsF.47 赋值运算符应该返回T&。
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。这保证了和标准库类型的一致性而且遵守了“像整数一样动作”的准则。
译者注:“像整数一样动作”应该说的是,使用重载的赋值运算符的代码,看起来要和使用整数赋值运算符的代码具有同样的形式。
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--形式的代码,但这种代码的普遍性还不足以将其视为和对标准类型一致性的违反。
class Foo
{
public:
...
Foo& operator=(const Foo& rhs) {
// Copy members.
...
return *this;
}
};
This should be enforced by tooling by checking the return type (and return value) of any assignment operator.
应该强制对任何赋值运算符的返回值类型(和返回值)进行工具化检查。
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】,轻松学习每一天!
有任何疑问,欢迎留言提问或讨论。
面向对象设计,面向对象编程,面向对象思考!