<分区>
我正在尝试使用引用和指针做一些事情,但我发现了一些我根本不理解的事情。
这是我的代码:
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "con\n"; }
~A() { cout << "des\n"; }
void f() { cout << "bla" << endl; }
};
A &createA()
{
A *a = nullptr;
{
A b;
a = &b;
cout << *&a << endl;
}
return *a;
}
int main()
{
A &b(createA());
cout << &b << endl;
b.f();
system("pause");
return 0;
}
输出:
con
des
0058FE0B
0058FE0B
bla
Press any key to continue . . .
如您所见,即使对象本身已被销毁,成员函数 f() 仍会被调用。为什么?我认为应该有一些错误,但函数 f() 确实被调用并且它事件正确地执行了所有操作,为什么?