当前位置:网站首页>单例的常用创建和使用方式
单例的常用创建和使用方式
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;
}边栏推荐
- Mongodb of NoSQL - 03 mongodb CRUD
- 初识-软件测试
- 深度解析当贝盒子B3、腾讯极光5S、小米盒子4S之间的区别
- 第十章 设置结构化日志记录(二)
- Websocket and socket IO case practice
- Nodejs get get/post request parameters
- 7-1 数的范围
- 班主任让开股票账户,在挖财理财开户安全吗?
- 5+API,清除应用缓存
- Investment planning and forecast report on the future direction of China's smart agriculture during the 14th five year plan (2022)
猜你喜欢

MySQL 自定义函数时:This function has none of DETERMINISTIC, NO SQL 解决方案

Photoshop 2022 23.4.1增加了哪些功能?有知道的吗

NoSQL mongodb - 04 mongodb database and web service combination case
Adobe Acrobat prevents 30 security software from viewing PDF files or there are security risks

Tiger DAO VC产品正式上线,Seektiger生态的有力补充

深度解析当贝盒子B3、腾讯极光5S、小米盒子4S之间的区别

Less than 40 lines of code to create a blocprovider

Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology

Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology

环形队列php
随机推荐
Generate JDE dot train
guacamole安装
Lodash common methods (filtering, anti shake...)
源码学习:AtomicInteger类代码内部逻辑
Ubuntu安装配置PostgreSQL(18.04)
ES6模块
Xiaolong 888 was released, Xiaomi 11 was launched, and 14 manufacturers carried it in the first batch!
.NET MAUI 性能提升
Investment planning and forecast report on the future direction of China's smart agriculture during the 14th five year plan (2022)
由错误<note: candidate expects 1 argument, 0 provided>引发的思考
Examples of how laravel uses with preload (eager to load) and nested query
Research on the current situation of China's modified engineering plastics market and demand forecast analysis report 2022-2028
File remote synchronization and backup artifact Rsync
ES6:迭代器
初识-软件测试
Websocket and socket IO case practice
NoSQL mongodb - 02 mongodb server installation, mongodb shell, basic concepts and visualization tools
栈,后入先出
TP5 thinkphp5 extension package think Mongo operation mongodb time interval range query
做自媒体视频的各种常用工具合集奉上