被破坏的C++对象的数据仍然可以访问?

sym*_*nic 1 c++

在以下代码中,该getObj()函数返回对本地对象的引用.这显然是非常糟糕的,因为当函数返回时对象被破坏(ctor和dtor输出强调对象的生命周期).正如所料,编译器(gcc44)给出了相应的警告.

#include <iostream>

class Blah {

private:
    int a_;

public:
    Blah(int a) : a_(a) { std::cout << "Constructing...\n"; }
    ~Blah() { std::cout << "...Destructing\n"; }
    void print() { std::cout << a_ << "\n"; }
};

Blah& getObj() 
{
    Blah blah(3);
    return blah; // returning reference to local object
}

int main()
{
    Blah& b = getObj();
    b.print(); // why does this still output the correct value???

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,调用print()明显被破坏的对象仍然会打印私有变量的正确值a_.这是输出:

构建......
...破坏
3

怎么会这样?我本来希望所有的对象数据都被销毁.

jua*_*nza 6

它被称为未定义的行为.任何事情都可能发生.你所看到的只是"任何东西"的一个子集.