为什么即使我使用malloca分配了内存,也会调用析构函数

Why destructor getting called even though I have allocated memory using malloca?

本文关键字:调用 析构函数 内存 分配 malloca 为什么      更新时间:2023-10-16
#include<iostream>
#include<stdlib.h>
using namespace std;
class Test
{
public:
    Test()
    {
        cout<<"constructor called"<<endl;`
    }
    ~Test()
    {
        cout<<"Destructor called"<<endl;
    }
};
int main()
{
    ///constructor called
    Test *t=new Test();
    free(t);
    Test *t2=(Test*)malloc(sizeof(Test));
    ///destructor getting called
    delete t2;
    getchar();
    return 0;
}

delete t2的语义是调用析构函数,然后释放空间。

这里的代码有未定义的行为,因为您不能使用free函数来释放new分配的空间。不能使用delete关键字来释放malloc分配的空间

代码甚至无法编译:Malloc返回一个指向已分配内存的指针,所以不是:

Test t2=(Test)malloc(sizeof(Test));

你需要做

Test * t2=(Test*)malloc(sizeof(Test));

malloc是c语言,delete是c++语言。

在'malloc'/' callloc '之后是'free'。'free'只释放内存。

"new"之后是"delete"。'delete'调用析构函数,然后释放内存