C++ 单例模式
2018-06-17 20:42:14来源:未知 阅读 ()
C++实现单例模式的三种方法
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <mutex>
using namespace std;
class singleton
{
public:
static singleton *getInstance();
private:
singleton() = default;
singleton(const singleton &sle) {}
static mutex mtx;
static singleton *instance;
};
singleton *singleton::instance;
mutex singleton::mtx;
// 懒汉式
singleton *singleton::getInstance()
{
mtx.lock();
if (instance == NULL)
{
instance = new singleton;
}
mtx.unlock();
return instance;
}
// 双重锁式
singleton *singleton::getInstance()
{
if (instance == NULL)
{
mtx.lock();
if (instance == NULL)
{
instance = new singleton();
}
mtx.unlock();
}
return instance;
}
// 饿汉式
singleton *singleton::instance = new singleton;
singleton *singleton::getInstance()
{
return instance;
}
void test()
{
singleton *sle1 = singleton::getInstance();
singleton *sle2 = singleton::getInstance();
cout << sle1 << endl;
cout << sle2 << endl;
/*singleton sle3 = *sle1;
cout << &sle3 << endl;*/
}
int main(void)
{
test();
system("pause");
return 0;
}
要适当的注销代码...
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:C++的六个函数
下一篇:快速数论变换(NTT)小结
- C++ 转换函数搭配友元函数 2020-06-10
- C++ 自动转换和强制类型转换(用户自定义类类型) 2020-06-10
- C++ rand函数 2020-06-10
- C++ 友元函数 2020-06-10
- C++ 运算符重载 2020-06-10
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
