我试图用一个简单的例子来解释我的问题
typedef function<bool()> TaskCallback;
class Task
{
public:
Task(TaskCallback task_callback) : task_callback(task_callback)
{
long_string_test = "This is a long string 0123456789ABCDEF 0123456789ABCDEF 0123456789ABCDEF";
xTaskCreate(Task::RunTask, "task_name", 2560, this, 3, &task_handle);
}
~Task()
{
while(1); //Breakpoint: The destructor is never called
}
private:
static void RunTask(void* params)
{
Task* _this = static_cast<Task*>(params);
_this->task_callback(); //The program crashes here because task_callback doesn't exist
}
string long_string_test;
TaskCallback task_callback;
TaskHandle_t task_handle;
};
main.cpp
static bool Init_task() { }
void main()
{
Task task(Init_task);
vTaskStartScheduler();
//We should never get here as control is now taken by the FreeRTOS scheduler
while(1);
}
如果通过long_string_test
函数中的调试器检查字符串RunTask
的值,我会发现它具有一个奇怪的值,就好像该字符串已被破坏。但是从未调用过Task
类的析构函数。
如果我在程序下面更改“ main.cpp”,则该程序可以正常工作,我认为编译器会进行某种优化:
static bool Init_task() { }
Task task(Init_task);
void main()
{
vTaskStartScheduler();
//We should never get here as control is now taken by the FreeRTOS scheduler
while(1);
}
ps.s。显然,编译器优化已禁用
terminate,
- 调用库I / O函数,
- 通过易失的glvalue执行访问,或
- 执行同步操作或原子操作。
[注意:这旨在允许编译器转换,例如删除空循环,即使无法证明终止也是如此。 —尾注]
~Task()
{
while(1); //Breakpoint: The destructor is never called
}
都不做,因此编译器是免费的,而忽略它。
int* test;
static void RunTask(void* params)
{
Print(*test); //The "test" pointer has a random value
}
void main()
{
int temp = 9999;
test = &temp;
xTaskCreate(RunTask, "task_name", 2560, NULL, 3, NULL);
vTaskStartScheduler(); //It seems that FreeRTOS clears the main() stack
//We should never get here as control is now taken by the FreeRTOS scheduler
while(1);
}