单片机中C++的局部static变量的初始化仍然遵循控制流
实验
执行如下测试代码
class Test
{
public:
Test()
{
bsp::di::Console().WriteLine("构造");
}
};
void test_func()
{
bsp::di::Console().WriteLine("第一条语句");
static Test test;
}
执行两次 test_func
,在串口观察输出
可以看到
static Test test;
的构造发生在
bsp::di::Console().WriteLine("第一条语句");
之后。
使用的编译器为 arm-none-eabi-g++ ,单片机为 stm32h743iit6.
结论
即使在单片机中,局部 static 变量也严格遵循控制流。也就是说可以用局部 static 来实现单例,并且在局部 static 的定义语句前面插入禁用中断,禁止任务调度等代码来保证线程安全和可重入。