最近我在复习C++中的运算符重载,按照建议为“=”的运算符重载返回*this
的引用。但是随后我发现了一个问题:
#include <iostream>
using namespace std;
class MyClass
{
int num = 4;
public:
MyClass() = default;
MyClass(int x) : num(x) {}
void getnum(int x)
{
num = x;
}
void shownum()
{
cout << num << '\n';
}
MyClass& operator = (const MyClass& obj) // works even without const
{
this->num = obj.num;
return *this;
}
~MyClass() = default;
};
int main()
{
MyClass x, y(5), z(7);
z = MyClass(8) = y; // temporary object return reference
x.shownum();
y.shownum();
z.shownum();
}
尽管涉及到一个临时对象MyClass(8)
,该代码不会导致UB
,之后将其与y
相等(没有问题),但然后它的引用将被发送以与z
相等。为什么这里不会出现悬挂引用
问题?为什么重载函数可以在临时对象MyClass(8)
上工作而不需要const MyClass&'
?