【发布时间】:2021-03-23 03:46:11
【问题描述】:
调用delete 调用类的析构函数,但调用free() 不会。
这会导致内存泄漏吗?如果不是,为什么?
#include <iostream>
#include <cstdlib>
using namespace std;
class x{
public:
int a;
~x(){cout<<"destroying"<<endl;}
};
int main() {
x *y = (x*)malloc(sizeof(x));
free(y);
x *z = new x;
delete z;
return 0;
}
【问题讨论】:
-
它有未定义的行为,所以它可能导致任何事情或根本没有。
-
new必须与delete匹配(并且new[]与delete[]匹配)。free是malloc的匹配项。 -
编辑后,
x *y = malloc(sizeof(x));行甚至无法编译。
标签: c++ destructor free delete-operator