简体   繁体   中英

Calling destructor to free dynamically allocated memory

Let consider this code:

#include <iostream>
class A{
public:
        ~A() {}
};
int main(){
        A *p = new A();
        p->~A();
        return 0;
}

I would like to know if the memory of the object A pointed by p is freed or we must to call delete p;

The memory was not freed. The destructor destroys the object but does not free the memory. How could it? You can destroy objects that are dynamically allocated, are on the stack, are globals, and so on. The destructor has no idea what is needed, if anything, to release the memory.

Memory was allocated using operator new and will be freed (deallocated) using operator delete , not your object's destructor.

We should not confuse the object lifetime with dynamic memory management .

It is not A' s destructor role to free the allocated memory and it should not be called explicitly. It is simply a member function that gets called when your object gets destroyed. And it will get destroyed after you call the delete .

Replace:

p->~A();

with:

delete p;

Now your objects gets destroyed and the allocated memory gets deallocated.

调用析构函数或任何其他成员函数之间没有区别,除了一件事 - 您不应该这样做,除非您想将对象分配与其构造和销毁分开。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM