我已经看过很多教程并尝试在stackoverflow上找到答案,但没有成功。
我不确定的是什么;当重载运算符时,是否有值得通过值或引用返回的实践?
例如
Class &operator+(){
Class obj;
//...
return obj;
}
或同样的事情,但按价值
Class operator+(){
Class obj;
//...
return obj;
}
我想提一下,我注意到在几乎90%的情况下,返回同一个对象(*this
)时,会在返回的同一个对象上引用。有人可以解释为什么会这样吗?
答案 0 :(得分:3)
...当重载运算符时,有什么时候通过值或引用返回?
是的,有一些规范形式found here。他们都没有相同的形式 - 他们因运营商而异。一般建议是遵循内置类型的语义。与所有函数一样,一般规则仍然适用,例如不返回对局部变量的引用(如OP中所示)。
E.g。 (在上面的链接中找到)给出问题的加法运算符;
class X
{
public:
X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
{ // but often is, to modify the private members)
/* addition of rhs to *this takes place here */
return *this; // return the result by reference
}
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c
const X& rhs) // otherwise, both parameters may be const references
{
lhs += rhs; // reuse compound assignment
return lhs; // return the result by value (uses move constructor)
}
};
operator+
是非成员方法(通常为friend
)并按值返回 - 这对应于内置类型的语义。同样,operator+=
是一个成员方法,并通过引用返回(*this
的更新版本)。
...返回同一个对象(
*this
)时,正在返回的同一对象上引用。有人可以解释为什么会这样吗?
如果返回类型是按值(X operator+
),则return *this;
表示生成并返回当前对象的副本(this
指向的内容)。
如果返回类型是引用(X& operator+
),则return *this;
表示返回对当前对象(this
所指向的内容)的引用(即不副本)。
答案 1 :(得分:1)
通过引用从operator+
返回的第一个选项是错误的,因为您通过引用返回本地对象,但是在操作符函数体结束后本地对象不再存在。一般为:
+=
或-=
之类的变体运算符通过引用返回,因为它们返回变异对象本身(通过:return *this;
)+
或-
等普通运算符应按值返回,因为需要构造一个新对象来保存结果。