【问题标题】:return type is a reference - what will happen exactly?返回类型是一个引用——究竟会发生什么?
【发布时间】:2017-06-10 08:00:39
【问题描述】:
LinkedList& LinkedList::operator= (const LinkedList& other)
{
if(this == &other)
{
return *this;
}
/* some other codes if this != &other */
}
当代码return * this 执行时,返回的是this 的地址吗?这意味着接收该值的 LHS 上的变量将具有与 this 相同的地址?
【问题讨论】:
标签:
c++
pointers
reference
return
【解决方案1】:
假设=-operator 的返回值是=(a,b) 返回的值。在中缀表示法中使用此运算符的示例。
a=b=2; //this is equivalent to a=(b=2);
print(a);
此代码-sn-p 应返回“2”,因为当执行 b=2 时,它会返回右侧的值(或者换句话说,b 的新值,左侧) ,然后作为a= 的右轴提供。
所以对于链表来说,当它已经等同于 rhs 时,它只会返回 lhs(“this”)。可能是某种形式的优化,通过在发现操作员实际上不需要更改任何东西时提前终止代码。
【解决方案2】:
operator * 通常有签名
MyClass& operator*(MyClass *)
const MyClass& operator*(const MyClass *)
也就是说,它需要一个“指向类型的指针”并返回一个“对类型的引用”
this 始终是一个指针,指向运行该方法的类的实例。*this 因此是对该实例的引用。
注意比较是(this == &other),它取了other的地址来和this指针比较。