用 static 变量的特性来模拟出std::call_once

188 阅读1分钟
  • 直接上代码,考察两点
    1. static静态变量只能初始化一次,借助此实现std::call_once
    2. 何时初始化该static bool,取决于在哪定义该静态变量,在局域则是程序执行该定义变量时初始化它;若是全局的static bool而是用到该变量才初始化它,则是执行main前就call_once
      void fun()
      {
              printf("fun run \n");
      };
      
      bool fun1()
      {
              printf("fun1 run \n");
              return true;
      };
      int main()
      {	
              fun();
              static bool flag = fun1();
              return 0;
      }  
      // result  
      // fun run and then fun1 run