简体   繁体   English

使用 malloc 调用 free() 来释放动态分配的 memory 的析构函数

[英]Destructor to call free() to free dynamically allocated memory using malloc

In C++, if I have some dynamically allocated memory using malloc, can I free the same by calling free() from destructor and then explicitly call the destructor via class object? In C++, if I have some dynamically allocated memory using malloc, can I free the same by calling free() from destructor and then explicitly call the destructor via class object?

Trying to do that but getting an exception.试图这样做,但得到一个例外。

Is it now allowed?现在允许吗?

So here I'm explicitly calling the destructor.所以在这里我明确地调用了析构函数。 Is this allowed?这是允许的吗? I mean, I'm calling it to free memory.我的意思是,我调用它来释放 memory。 I did read that after the scope, the destructor is called implicitly.我确实读过在 scope 之后,隐式调用了析构函数。 Does this mean the free() will try to happen twice?这是否意味着 free() 将尝试发生两次?

My code snippet:我的代码片段:

class School
{
    int a;
};

class Test
{
    public:
    School* school;
    void Run()
    {
        school = (School*)malloc(sizeof(School));
    }
    
    ~Test()
    {
        if (NULL != school)
        {
            free(school);
            school = NULL;
        }
    }
};

int main()
{
    Test t;
    t.Run();
    t.~Test();
    return 0;
}

Your code destroys t twice.您的代码破坏了t两次。 It is destroyed first when you call the destructor and then again when it goes out of scope.当你调用析构函数时它首先被销毁,然后当它退出 scope 时再次被销毁。 You cannot create one object and then destroy two objects.您不能创建一个 object 然后销毁两个对象。

You can explicitly call the destructor, and that has sense whenever you create the object using an placement new .您可以显式调用析构函数,并且每当您使用放置 new创建 object 时,这都是有意义的。

You may get an exception if you have the opposite order of operations.如果您有相反的操作顺序,您可能会遇到异常。 First you need to call the destructor, as it needs to free all the resources that the object may have allocated.首先,您需要调用析构函数,因为它需要释放 object 可能已分配的所有资源。 You need to call the free function only after all resources of the object are deallocated/destroyed.只有在 object 的所有资源都被释放/销毁后,您才需要调用free的 function。 For example:例如:

struct S {
    ~S() {
        delete ptr;
    }
    int *ptr;
};

int main() {
    char *buf = (char*) malloc(sizeof(S)) ;
    S *s = new (buf)S();
    // Do not call free here as the destructor needs to access the s.ptr:
    //free(buf);
    s->~S();
    free(buf);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM