为什么即使我使用malloca分配了内存,也会调用析构函数
Why destructor getting called even though I have allocated memory using malloca?
#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'调用析构函数,然后释放内存
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 为什么在运算符删除中不调用析构函数?
- C++ 调用析构函数后动态模板队列"double free or corruption (out)"
- 在 postOrderDelete 上调用析构函数时引发的异常