...当重载运算符时,是否有一些实践何时按值或按引用返回?
是的,这里有一些规范形式。它们并非都具有相同的形式 - 它们因运营商而异。一般建议是遵循内置类型的语义。与所有函数一样,一般规则仍然适用,例如不返回对局部变量的引用(如 OP 中所示)。
例如(在上面的链接中找到)给定问题的加法运算符;
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+
是一个非成员方法(通常作为 a friend
)并按值返回 - 这对应于内置类型的语义。类似地,operator+=
是成员方法并通过引用返回(的更新版本*this
)。
...当返回相同的对象 ( *this
) 时,被返回的相同对象引用。有人可以解释为什么会这样吗?
如果返回类型是按值 ( X operator+
),则return *this;
意味着this
制作并返回当前对象(由 指向的对象)的副本。
如果返回类型是按引用 ( X& operator+
),则return *this;
意味着返回对当前对象(由 指向的对象)的引用this
(即不是副本)。