Delete task but local variables (objects) are not correctly deleted with the destructor

parmi wrote on Friday, August 23, 2019:

I realized that the destructors of the objects that I create locally within a task are not called when the task is eliminated.

I think this happens because the function of the task does not exit properly from its scope, and therefore the destructors of local objects are not called.

How can I solve this problem?

main.cpp

class MyClass
{
    public:
    MyClass()
    {
        buffer = (char*)malloc(5);
    }
    
    char* buffer;
    
    //It is never called
    ~MyClass()
    {
        delete buffer;
    }
};

static void MyTask(void *pvParameters)
{
    MyClass my_class = MyClass();
    
    //Delete this task
    vTaskDelete(NULL);
}

parmi wrote on Friday, August 23, 2019:

Sorry duplicate post
https://www.freertos.org/FreeRTOS_Support_Forum_Archive/December_2017/freertos_C_RAII_in_FreeRTOS_f0d9a348j.html

In any case, are there no other solutions?

hs2sf wrote on Friday, August 23, 2019:

Just call vTaskDelete() at the very end of your destructor(s).
See the very good C++ wrappers by Richard here

richard_damon wrote on Friday, August 23, 2019:

You need to make all the resources be cleaned up before you call the vTaskDelete function. My wrapper functions that HS2 pointed to will (if vTaskDelete is enabled) delete the task when then task function returns. An alternative is to change you code to be like:

static void MyTask(void *pvParameters)
{
   {
       MyClass my_class = MyClass();
   }
    //Delete this task
    vTaskDelete(NULL);
}

Adding a scope within which the instance is created, and thus destroyed on exiting, before the delete is called

parmi wrote on Thursday, August 29, 2019:

thank you, I will use this solution =)