简体   繁体   English

即使我使用 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;
}

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.

相关问题 为什么即使我没有为它分配内存也能工作? - Why does gets work even when I have not allocated memory to it? ptr_vector-_CrtDumpMemoryLeaks()-即使调用了析构函数,内存也会泄漏 - ptr_vector - _CrtDumpMemoryLeaks() - memory leaks even though destructor is called 我是否必须调用析构函数来释放动态分配的 memory? - do i have to call destructor to free the dynamically allocated memory? 为什么派生类析构函数被调用,即使基类析构函数不是虚拟的,如果将对象创建为引用 - Why derived class destructor called even though base class destructor is not virtual if object is created as reference 即使删除了析构函数,为什么我仍可以进行匿名联合? - Why can I make an anonymous union even though the destructor is deleted? 即使未分配内存,strcpy也能正常工作 - strcpy works fine, even though memory is not allocated 代码显示“取消引用 null ptr”,即使指针的 cout 指向 memory 地址。 _malloca 用于分配 memory - Code showing “dereferencing null ptr” even though a cout of the pointer points to a memory address. _malloca is used to allocate memory 在C ++中,即使调用了delete,进程何时保留已分配的内存? - In C++, when does a process retain allocated memory even though delete is called? 为什么复制构造函数被调用,即使我实际上是在C ++中复制到已经创建的对象? - why copy constructor is getting called even though I am actually copying to already created object in C++? 使用共享指针进行双重删除,即使对象仍然存在shared_ptr,也会调用其析构函数 - Double Delete using Shared Pointers, even though there is still a shared_ptr to the object, its destructor is being called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM