运算符重载
iarray<T>& operator = (iarray<T>& v)
为什么返回类型是 iarray
而不是 iarray
?
更新
有人可以详细说明为什么iarray
?
iarray<T>& operator = (iarray<T>& v)
Why the return type is iarray<T>&
not iarray<T>
?
UPDATE
Can someone elaborate in great detail why iarray<T> const &v
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您不想仅仅为了链接而返回数组的副本。返回引用是一个更好的选择,因为它不会导致构造副本。
Because you don't want to return a copy of the array just for the sake of chaining. Returning a reference is a better option as it doesn't result in a copy being constructed.
因为这样你就可以有效地链接它们,例如。
请参阅C++ 常见问题解答。
Because then you can chain them efficiently, eg.
See the C++ FAQ.
因为分配的结果是对刚刚分配的内容的引用。例如,
a = b
的结果应该是对a
的引用,因此您可以像c = a = b;
中那样将它们链接在一起这实际上是 a = b; c = a;。 (是的,人们在极少数情况下喜欢这样做;不,我不知道为什么将其分成两行如此困难。)因此您的代码应该如下所示:因为赋值操作没有必要改变右侧;这是意想不到的行为。如果您的对象中有一些奇怪的东西需要更改,例如引用计数,那么您应该更喜欢声明该部分
mutable
而不是不允许const
右侧表达式。您可以为const
参数传递一个非const
值,但反之则不然。Because the result of an assignment is a reference to what just got assigned. For example, the result of
a = b
should be a reference toa
so you can chain them together like inc = a = b;
which is effectivelya = b; c = a;
. (Yes, people like doing this on rare occasions; no, I don't know why it's such a hardship to break it into two lines.) Thus your code should look like:Because an assignment operation has no business changing the right-hand side; it is unexpected behavior. If you have some funky thing in your object that needs to change, like a reference count, then you should prefer declaring that one part
mutable
over disallowingconst
right-hand side expressions. You can pass a non-const
value in for aconst
parameter, but the reverse is not true.