引用的对象不存在

#include <iostream>
using namespace std;


class A
{
public:
A(int x) { this->x = x; }
~A() {};
int get_x() { return x; }

private:
int x;
};


A& func()
{
A a(33); // 局部变量超过作用域会回收
return a;
}

int main()
{
A& r = func();
cout << r.get_x() << endl;

return 0;
}

输出:

7599612  // 一个随机数

如果将主函数​​A& r = func();​​​改成​​A r = func();​​​ func 函数返回值改成​​A​​​去掉​​&​​,按值返回对象的副本。

输出:

33