C++11中静态局部变量初始化的线程安全性详解编程语言
2023-06-13 09:11:47 时间
在C++标准中,是这样描述的(在标准草案的6.7节中):
such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
分析标准关于局部静态变量初始化,有这么几点要求:
变量在代码第一次执行到变量声明的地方时初始化。 初始化过程中发生异常的话视为未完成初始化,未完成初始化的话,需要下次有代码执行到相同位置时再次初始化。 在当前线程执行到需要初始化变量的地方时,如果有其他线程正在初始化该变量,则阻塞当前线程,直到初始化完成为止。 如果初始化过程中发生了对初始化的递归调用,则视为未定义行为
所以一下这种方式,直接就是线程安全的
class Foo public: static Foo *getInstance() static Foo s_instance; return s_instance; private: Foo() {} };
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/17535.html
cjava相关文章
- EasyC++47,全局变量
- c++全局变量与静态变量「建议收藏」
- C++Qt入门(1)—Qt简介,第一个Qt程序,Qt按钮
- C++_vector操作
- 【C++ spdlog】C++ 日志库 spdlog 使用
- C++ mysql connector使用方法「建议收藏」
- C++继承的基本语法与三种继承方式
- 邻接矩超详解(C/C++)
- 判断DLL文件是C/C++动态链接库还是.NET程序集及查看DLL依赖
- C++构造函数的作用_c++什么是构造函数
- C++动态库和静态库_动态库和静态库调用方法
- C++字符串加密_c++字符串连接函数
- c++的链表-C++链表
- c++的链表-链表入门(C++)
- C/C++ Npcap包实现数据嗅探
- C/C++ 静态编译SQLITE数据库API
- Visual Studio Code (VS Code) – C++ 入门
- [C++STL教程]4.map超强的容器,它终于来了!零基础都能理解的入门教程
- c++基础篇之C++ 模板
- C++ 类中特殊的成员变量(常变量、引用、静态)的初始化方法详解编程语言
- C++静态成员变量详解
- C++静态绑定和动态绑定(无师自通)
- C++中的单例模式(普通,2B,文艺)