为什么operator =返回引用而不是const引用 [英] Why operator= returns reference not const reference
问题描述
原来的问题是与重载operator =相关,我喜欢分享我的发现,因为对我来说这是非常重要的。
我不能想象合理的例子使用(a = b)作为左值。
在IRC和google的帮助下,我发现了下一篇文章:
http://msdn.microsoft.com/en-us/magazine/cc301415.aspx
The original question is related to overloading operator= and I like to share my findings as it was nontrivial for me to find them. I cannot imagine reasonable example to use (a=b) as lvalue. With the help of IRC and google I've found the next article: http://msdn.microsoft.com/en-us/magazine/cc301415.aspx
它提供了两个例子。
(a=b)=c
f(T& );
f(a=b)
但两者都不好,我相信是不好的做法。
第二个给我相同的感觉。
but both a bit not good, and I believe that it is bad practice. The second one give me the same feeling. Could you provide more good examples why it should be non constant?
推荐答案
一个很好的理由是,其中一个标准中要求在标准容器中可用的类 X
的要求是,表达式 a = b
类型 X&
(其中 a
是类型 X
和 b
是类型 X
的右值。
One good reason is that one of the requirements in the standard for a class X
to be useable in the standard containers is that the expression a = b
must have type X&
(where a
is an lvalue of type X
and b
is an rvalue of type X
).
这篇关于为什么operator =返回引用而不是const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!