当前位置:网站首页>单例的常用创建和使用方式
单例的常用创建和使用方式
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;
}边栏推荐
- MySQL optimization - index (what is an index?)
- JS how to judge when data contains integer and floating-point types. Floating-point decimals retain two digits after the decimal point
- 小程序中控件里面的内容较多,让其支持滚动的良好方案
- Redis learning - 04 persistence
- Demand scale forecast and investment competitiveness analysis report of China's new material market 2022-2028
- Xiaobai lazy special-win10-win11 one click installation version
- 7-2 数的三次方根
- Research and development practice of Kwai real-time data warehouse support system
- Adobe Acrobat阻止30款安全软件查看PDF文件 或存在安全风险
- Examples of how laravel uses with preload (eager to load) and nested query
猜你喜欢

【网络是怎么连接的】第二章(下):一个网络包的接收

File remote synchronization and backup artifact Rsync

processsing 函数random

国标GB28181协议EasyGBS级联宇视平台,保活消息出现403该如何处理?

Fengshentai old shooting range Kali series

Several rare but useful JS techniques

Implementing mixins scheme in applet

Installing MySQL under Linux (RPM package installation)

Mysql8 master-slave replication

openlayers 绘制动态迁徙线、曲线
随机推荐
Redis learning - 03 transaction
深入解析 MySQL binlog
SQL injection
【网络是怎么连接的】第一章:浏览器生成消息
无人机遥感在森林监测的部分应用研究案例总结
NoSQL mongodb - 01 introduction to NoSQL and mongodb
初识-软件测试
New routing file in laravel framework
轻流完成与「DaoCloud Enterprise 云原生应用云平台」兼容性认证
Processing 多面体变化
NoSQL mongodb - 02 mongodb server installation, mongodb shell, basic concepts and visualization tools
Research and development practice of Kwai real-time data warehouse support system
TP5 thinkphp5 report serialization of'closure'is not allowed
NoSQL mongodb - 04 mongodb database and web service combination case
Typescript learning (I) type
710. 黑名单中的随机数
Configuring Apache digest authentication
Redis learning - 05 node JS client operation redis and pipeline pipeline
【网络是怎么连接的】第二章(上): 建立连接,传输数据,断开连接
KITTI Detection dataset whose format is letf_top_right_bottom to JDE normalied xc_yc_w_h