析构函数是真的破坏内存还是在对象的生命周期即将结束之前运行?

is Destructor really destroy memory or just runs before the lifetime of object is going to end?

there are few question like this but not exactly same so please care to read whole question before cast it as duplicate one

1。使用 new 关键字创建的对象(动态对象)。

我们明确地使用 delete 关键字来取消分配那里的内存。因此,当程序遇到 delete 关键字时,它会感觉到对象将要结束,因此它会在那里运行析构函数。析构函数是否在那里取消分配内存?我不这么认为,就好像我们手动创建析构函数并且不编写任何代码一样,只是空析构函数仍然会发生取消分配。意味着我觉得析构函数运行然后控制权回到 delete 关键字然后内存取消分配完成。

如有错误请指正

如果我是对的 那么如果我在指针的帮助下为这些动态对象手动调用析构函数会怎样p->~destructor()(其中 p 是指向这些动态内存的 ptr ) 是否会取消分配内存? 如果不是 那么当 delete 命令它不会进入 undefined behavior UB 对吗? 如果是 但是如何取消分配内存,因为析构函数不会取消分配内存并且它也没有 delete 命令。 (我知道当它到达 delete 时它会进入 UB

2。本地对象

当作用域结束时,内存就会被破坏。因此,当程序遇到范围结束时,它会感觉到特定对象将要结束,因此它运行它的析构函数,然后控制返回到调用的位置(就在范围结束之前),然后变量离开范围并销毁内存。

如有错误请指正

如果我是对的 那么如果我为这个本地对象手动调用析构函数会怎么样 a. ~destructor (其中 a 是本地对象)它是否会破坏内存? if not while scope is going to end destructor invokes, then it not goes into UB right. 如果是那么它是如何破坏内存的。因为析构函数不取消分配内存并且它也没有到达范围的末尾。

3。静态对象

我认为 staticlocal 对象之间的唯一区别是 static 在程序将要结束时被销毁,而 local 在范围将要结束时被销毁,所以关于析构函数适用于 local objects,对象的销毁也适用于 static objects

4。如果析构函数不取消分配内存,那么它实际上做了什么?

我的老师说析构函数只是给一点时间告诉我们这些对象将被销毁,这样我们就可以完成一些关于这些对象的事情,他是对的吗?另外请告诉加分析构函数的作用。

or just runs before the lifetime of object is going to end?

明确一点:对象的生命周期结束和析构函数的调用发生在同一个时间点,不是一个接一个。

is destructor de-allocate there memory ?

不一定。有关详细信息,请参见以下示例。

  1. if destructor do not de-allocate memory then what actually it does ?

让我们考虑以下 class:

struct example : base {
    another_class member;
    ~example() {
        // destructor body
    }
};

example的析构函数首先执行“析构体”,然后执行所有子对象的析构函数(本例为memberbase)。如果主体或任何子对象的析构函数释放了一些内存,那么这就是析构函数所做的。但是被销毁对象的内存一般不会被析构函数释放。

确实,delete 做了两件事:调用析构函数,释放存储空间。

what's about if I call destructor manually for these dynamic objects with help of pointer p->~destructor()(where p is ptr pointing to these dynamic memory)

这会破坏对象。

it will destroy memory or not ?

显式调用析构函数不会释放存储空间。

then what's about if I call destructor manually for this local object a. ~destructor (where a is local object) it will destroy memory or not ?

无论对象存储在何处,都不会通过显式调用析构函数来释放存储空间。

if not while scope is going to end destructor invokes, then it not goes into UB right.

如果自动存储中的销毁对象超出范围,则程序的行为未定义。

你可以看看C,它没有newdelete关键字。它有 mallocfreemalloc 只是分配内存而不初始化,free 只是释放。 C++ 有 newdeletenew 分配内存并调用构造函数,delete 调用析构函数并释放对象。

当您调用 ~destructor() 时,您只是清除了对象数据,但它仍然存在于内存中。

分配的变量 new 存储在堆上。局部变量存储在堆栈中,静态存储在数据段中。