Joh*_*e W 5 c++ operator-overloading return-by-reference c++11 return-by-value
我看过很多教程,并试图在 stackoverflow 上找到答案,但没有成功。
我不确定的是;在重载运算符时,是否有一些实践何时按值或按引用返回?
例如
Class &operator+(){
Class obj;
//...
return obj;
}
Run Code Online (Sandbox Code Playgroud)
或相同的东西但按价值
Class operator+(){
Class obj;
//...
return obj;
}
Run Code Online (Sandbox Code Playgroud)
我想提一下,我注意到在几乎 90% 的情况下,当返回相同的对象 ( *this) 时,会在返回的同一对象上引用。有人也可以解释为什么会这样吗?
...在重载运算符时,是否有一些实践何时按值或按引用返回?
是的,这里有一些规范形式。它们并不都具有相同的形式 - 它们因操作员而异。一般建议是遵循内置类型的语义。与所有函数一样,一般规则仍然适用,例如不返回对局部变量的引用(如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)
}
};
Run Code Online (Sandbox Code Playgroud)
是operator+一个非成员方法(通常作为 a friend)并按值返回 - 这对应于内置类型的语义。类似地,operator+=是一个成员方法并通过引用返回( 的更新版本*this)。
...当返回相同的对象 (
*this) 时,正在返回的同一对象上引用。有人也可以解释为什么会这样吗?
如果返回类型是按值 ( X operator+),则意味着创建并返回return *this;当前对象( 所指向的对象)的副本。this
如果返回类型是按引用 ( X& operator+) ,则return *this;意味着返回对当前对象( 所指向的对象this)的引用(即不是副本)。