首页 > 解决方案 > 为什么在取消引用/释放动态创建的对象之后,它仍然在 C++ 中被引用?

问题描述

#include<iostream>
#include<conio.h>

using namespace std;

class Marie{

public:
    int x;

    Marie(){
        cout<<"created";
    }

    ~Marie(){
        cout<<"hii i am destructor";
    }

    void ShowMarie() {
        cout<<"friends";
        x=5;
        delete this;  /*<--- here destructor called */
    }
};

int main(){
    Marie *ptr = new Marie;

    ptr->ShowMarie();

    cout<<ptr->x; /*<---- ptr is dangling pointer but it is still showing me the correct value.*/
    getch();
}
  1. 调用对象的析构函数后,它仍然像在内存中一样引用吗?为什么?
  2. 为什么我们需要为动态创建的对象显式调用析构函数delete this呢?
  3. 如果我们使用delete this;内部析构函数会发生什么?这是递归调用析构函数吗?

标签: c++delete-operatorthis-pointerexplicit-destructor-call

解决方案


调用对象的析构函数后,它仍然像在内存中一样引用吗?为什么?

删除指针不会将任何内存清零,因为这样做会占用 CPU 周期,而这不是 C++ 的意义所在。你所拥有的是一个悬空指针,并且可能是一个微妙的错误......Benj回答)。

为什么我们需要使用 delete this 为动态创建的对象显式调用析构函数?

如果对象是使用运算符 new() 的重载形式构造的,则需要手动调用析构函数,除非使用“std::nothrow”重载......Dietmar Kühl回答)。

如果我们使用删除这个;在析构函数里面会发生什么?这是递归调用析构函数吗?

一旦调用析构函数(第一次),对象的生命周期就结束了。因此,如果您从析构函数中调用对象的析构函数,则行为未定义......James McNellis回答)。

请在您未来的搜索中使用 stackoverflow 数据库,大多数时候您的问题已经有了答案。


推荐阅读