C ++在销毁引用对象后使用它

C++ using reference object after destroying it

我正在尝试使用引用和指针做一些事情,但我发现了一些我根本不理解的东西。

这是我的代码:

#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() 确实被调用并且它事件正确地执行了所有操作,为什么?

这里的编译器警告很漂亮self-explanatory:

main.cpp: In function 'A& createA()':
main.cpp:24:13: warning: function may return address of local variable [-Wreturn-local-addr]
     return *a;
             ^
main.cpp:19:11: note: declared here
         A b;
           ^

这是未定义的行为,简单明了。

当你使用 UB 时,编译器不需要警告你,但它允许假设你不会这样做,如果你这样做了,你没有保证将要发生的事情。该程序完全无效,任何事情 都可能发生。