当前位置:网站首页>单例的常用创建和使用方式
单例的常用创建和使用方式
2022-06-26 12:37:00 【老赵的博客】
- 目的:创建一个全局的单一实例,通过单一对象来调用类
- 创建
- 定义static 成员变量
- 构造函数私有化
- 防止多线程使用锁
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
if (m_Instance == NULL )
{
Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
if (m_Instance == NULL )
{
m_Instance = new Singleton ();
}
UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
}
return m_Instance;
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
}
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 0; }
static Singleton *m_Instance;
int m_Test;
};
Singleton *Singleton ::m_Instance = NULL;
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
Singleton ::DestoryInstance();
return 0;
}
边栏推荐
- 机组实践实验8——使用CMStudio设计基于基本模型机微程序指令(1)
- 【shell】生成指定日期之间的字符串
- 数字信号处理——线性相位型(Ⅰ、Ⅲ型)FIR滤波器设计(1)
- Adobe Acrobat prevents 30 security software from viewing PDF files or there are security risks
- 【网络是怎么连接的】第二章(下):一个网络包的接收
- 快手实时数仓保障体系研发实践
- EasyGBS如何解决对讲功能使用异常?
- 记一次phpcms9.6.3漏洞利用getshell到内网域控
- 国标GB28181协议EasyGBS视频平台TCP主动模式拉流异常情况修复
- File remote synchronization and backup artifact Rsync
猜你喜欢
Xiaolong 888 was released, Xiaomi 11 was launched, and 14 manufacturers carried it in the first batch!
不到40行代码手撸一个BlocProvider
Vivado 错误代码 [DRC PDCN-2721] 解决
Echart堆叠柱状图:色块之间添加白色间距效果设置
RSS rendering of solo blog system failed
openlayers 绘制动态迁徙线、曲线
The laravel dingo API returns a custom error message
Introduction to the four major FPGA manufacturers abroad
Mysql8 master-slave replication
Xiaobai lazy special-win10-win11 one click installation version
随机推荐
关于NaN的一些总结
File remote synchronization and backup artifact Rsync
详细实操分享,下班刷了两小时的搞笑视频,一个月收益7000多
简易数字电路交通灯设计
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
PHP calculates excel coordinate values, starting with subscript 0
Xiaobai lazy special-win10-win11 one click installation version
Echart堆叠柱状图:色块之间添加白色间距效果设置
美学心得(第二百三十八集) 罗国正
【shell】生成指定日期之间的字符串
goto语句实现关机小程序
Redis learning - 01 introduction, installation and configuration
Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
imagecopymerge
Photoshop 2022 23.4.1增加了哪些功能?有知道的吗
国标GB28181协议EasyGBS视频平台TCP主动模式拉流异常情况修复
Investment forecast and development strategy analysis report of China's rural sewage treatment industry in 2022
做自媒体视频的各种常用工具合集奉上
Vivado 错误代码 [DRC PDCN-2721] 解决
老司机总结的12条 SQL 优化方案(非常实用)