我有疑问,在这种情况下,我应该使用引用来重载运算符还是应该?
在没有参考的情况下,一切正常。
Vector & operator +=( const Vector & v )
{
this->x += v.x;
this->y += v.y;
return * this;
}
Vector operator +=( const Vector v )
{
this->x += v.x;
this->y += v.y;
return * this;
}
那么哪个选项更适合使用?
答案 0 :(得分:4)
使用参考号。否则,您将创建不必要的副本。 了解更多:pass by value or by reference。
Guaranteed copy elision,因为C ++ 17可能会出现,但仍然要遵循良好实践。
答案 1 :(得分:1)
重载@jangorecki
时的约定是返回非operator +=
引用。这源于const
运算符如何在C ++中原生使用原始类型。虽然在C ++中看到如下代码是非常非常不寻常的,但这是完全合法的:
+=
上面的代码仅在表达式int x = 137;
(x += 42) += 161;
作为左值对(x += 42)
求值时才有意义。因此,您应该返回对基础对象的引用。