c 线程安全的单例模式-std string与线程安全_这才是现代C++单例模式简单又安全的实现
2023-02-18 16:47:28 时间
前言
说到单例模式,很多人可能都已经很熟悉了,这也是面试常问的一个问题。对于单线程而言c 线程安全的单例模式,单例的实现非常简单,而要写出一个线程安全的单例模式,曾经有很多种写法。有兴趣的可以参考这篇文章《单例模式很简单?但是你真的能写对吗?》
简单实现
该文章中也提到c 线程安全的单例模式,由于C++11及以后的版本中,默认静态变量初始化是线程安全的。
The of such a is to occur the first
time passes its ; for
the , this means there’s the for a race
to define first.
写法如下:
//来源:公众号编程珠玑
//作者:守望先生
class Singleton{
public:
static Singleton& getInstance(){
static Singleton m_instance; //局部静态变量
return m_instance;
}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
protected:
Singleton() = default;
~Singleton() = default;
};
这里需要注意将其他构造函数设置为delete。避免对象被再次构造或者拷贝。
这种单例被称为Meyers’ 。
通用化
当然为了避免给每个对象都单独写个单例,也可以利用模板。
template
class Singleton
{
public:
static T& getInstance() {
static T t;
return t;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
protected:
Singleton() = default;
~Singleton() = default;
};
示例
举个简单的例子来看下吧:
//来源:公众号编程珠玑
//作者:守望先生
#include
template
class Singleton
{
public:
static T& getInstance() {
static T t;
return t;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
protected:
Singleton() = default;
~Singleton() = default;
};
class Test:public Singleton
{public:void myprint(){std::cout"test Singleton"
[1]: https://xuan.ddwoo.top/index.php/archives/585/
[2]: https://xuan.ddwoo.top/index.php/archives/596/
本文共 269 个字数,平均阅读时长 ≈ 1分钟
相关文章
- 一台电脑支持2个git账号:gitlab+github
- 资产收集神器-Goby工具
- phpStudy 2016搭建-upload-labs靶场
- Adobe Photoshop 2022(mac+windows全版本都有,包括最新的2023)
- PS 2021 软件安装包+安装教程(mac+windows全版本都有,包括最新的2023)
- 闻道Go语言,6月龄必知必会
- Go语言正/反向代理的姿势
- 你认识的C# foreach语法糖,真的是全部吗?
- PhpStudy 2016搭建-DVWA靶场
- c++——构造函数和析构函数
- 深入浅出学习Linux
- git相关问题解析,你想要的都有?
- Go | 闭包的使用
- linux安装stable diffusion2.0完整教程-还不会安装sd2.0?一篇文章教会你AI绘画
- arm Linux中dma的cache管理
- 嵌入式:数据处理指令详解
- golang go-sql-driver gorm 数据库报错 bad connection
- linux 命令之 ls 命令详解
- git help 查看命令手册
- 【6】python生成数据曲线平滑处理——(Savitzky-Golay 滤波器、convolve滑动平均滤波)方法介绍,推荐玩强化学习的小伙伴收藏