默认析构函数 V.S。简单定义的析构函数

Default Destructor V.S. A Simply Defined Destructor

我写这篇文章是为了分析一个class的析构函数的行为及其对内存释放的影响,但结果似乎让我有点意外:

class test {
public:
    test() {}
    ~test() {} //<-----Run the program once with and once without this line.
};

int main()
{
    test x;
    test *a(&x);
    cout << "a before memory allocation: " << a << endl;
    a = new test;
    cout << "a after memory allocation and before delete: " << a << endl;
    delete a;
    cout << "a after delete: " << a << endl;

    return 0;
}

使用默认析构函数的结果是: 但是对于我自己的析构函数,它是: 第二个结果不是错误的吗?因为我在某处读到:

the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage.

可能我没有理解正确(特别是因为使用了难懂的英语单词!)。你能给我解释一下为什么会这样吗? 我简单定义的析构函数和 C++ 默认析构函数之间到底有什么区别? 提前感谢您的帮助。

如果 a 是指向对象的(非空)指针,则操作 delete a 触发 a 指向的对象的析构函数(默认析构函数或特定的)并最终释放为此对象分配的内存。 a 指向的内存不再是有效对象,并且 a 不能再被取消引用。但是,delete a 不会将指针 a 的值设置回特定值。实际上我很惊讶 delete a 在你的例子中改变了 a 的值;我无法重现此行为。