你能解释一下返回值、引用值和 const 引用值的区别吗?
值(value):
Vector2D operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
非常量引用:
Vector2D& operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
常量引用:
const Vector2D& operator += (const Vector2D& vector)
{
this->x += vector.x;
this->y += vector.y;
return *this;
}
这样做有什么好处?我理解将 const 引用传递给函数背后的意义,因为您要确保不修改该引用指向函数内部的值。但是我对返回 const 引用的含义感到困惑。为什么返回引用比返回值好,为什么返回const引用比返回not-const引用好?
最佳答案
除非你写一些奇怪的东西,否则没有区别
(v1 += v2) = v3;
第一种情况,赋值给一个临时的,整体效果是v1 += v2
。
第二种情况,赋值给v1
,所以整体效果是v1 = v3
。
在第三种情况下,不允许分配。这可能是最好的选择,因为这种怪异几乎肯定是一个错误。
Why returning of reference is better than returning of value?
这可能更有效:您不必复制对象。
and why returning of const reference is better than returning of not-const reference?
你可以像上面的例子那样防止奇怪,同时仍然允许不那么奇怪的链接,比如
v1 = (v2 += v3);
但是,正如评论中所指出的,这意味着您的类型不支持与某些人认为可取的内置类型相同的 (ab) 使用形式。
关于C++ 返回值、引用、常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21778045/