[英]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;
}
The semantics of delete t2
is to call the destructor and then to free the space. delete t2
的语义是调用析构函数然后释放空间。
Here your code has undefined behavior since you cannot use the free
function to free the space allocated by new
.这里你的代码有未定义的行为,因为你不能使用
free
函数来释放new
分配的空间。 You can neither use the delete
keyword to free the space allocated by malloc
.您既不能使用
delete
关键字来释放malloc
分配的空间。
The code doesn't even compile: malloc return a pointer to the memory that been allocated, so instead of:代码甚至不编译: malloc 返回一个指向已分配内存的指针,因此而不是:
Test t2=(Test)malloc(sizeof(Test));
You need to do你需要做
Test * t2=(Test*)malloc(sizeof(Test));
malloc is in c and delete is in C++. malloc 在 c 中,delete 在 C++ 中。
After 'malloc'/'calloc' comes 'free'.在'malloc'/'calloc' 之后是'free'。 'free' only releases memory.
'free' 只释放内存。
After 'new' comes 'delete'.在“新”之后是“删除”。 'delete' calls the destructor and then releases memory.
'delete' 调用析构函数,然后释放内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.