c++单例模式
2016-03-21 22:34
375 查看
class Parent
{
public:
static Parent* GetInstense()
{
static boost::mutex p_mutex;
static Parent *S_singel;
if (NULL != S_singel)
{
return S_singel;
}
static boost::gurad_lock(p_mutex);//多线程中
if (NULL != S_singel)//当两个以上线程使用时,先获得锁的线程(其他线程在此处锁住)new对象,释放锁后,其他线程得到锁,这时候S_singel直接返回
{
return S_singel;
}
S_singel = new (std::nothrow)Parent;
if (NULL == S_singel)
{
cout << “error: new parent faired” << endl;
}
return S_singel;
}
private:
Parent();//构造函数和析构函数必须私有化,不允许直接new Parent,单例模式就只能通过GetInstense()获取
~Parent();
};
void main()
{
Parent * pParent = Parent::GetInstense();
if (NULL != pParent)
{
//
}
}
{
public:
static Parent* GetInstense()
{
static boost::mutex p_mutex;
static Parent *S_singel;
if (NULL != S_singel)
{
return S_singel;
}
static boost::gurad_lock(p_mutex);//多线程中
if (NULL != S_singel)//当两个以上线程使用时,先获得锁的线程(其他线程在此处锁住)new对象,释放锁后,其他线程得到锁,这时候S_singel直接返回
{
return S_singel;
}
S_singel = new (std::nothrow)Parent;
if (NULL == S_singel)
{
cout << “error: new parent faired” << endl;
}
return S_singel;
}
private:
Parent();//构造函数和析构函数必须私有化,不允许直接new Parent,单例模式就只能通过GetInstense()获取
~Parent();
};
void main()
{
Parent * pParent = Parent::GetInstense();
if (NULL != pParent)
{
//
}
}
相关文章推荐
- 编码用命令行执行的C语言词语统计程序
- 整理一些C++面试容易被问到的问题及其答案
- C++混合编程之idlcpp教程Python篇(2)
- C++ STL中map.erase(it++)用法原理解析
- C\C++代码优化的27个建议
- 【C++ STL学习与应用总结】目录
- c++的类的理解
- 错误:“LNK1169找到一个或者多个重定义的符号”
- 深入理解C指针学习笔记(一)
- 一起talk C栗子吧(第一百二十七回:C语言实例--查看main函数的参数)
- 在ubuntu下使用emacs对c++程序进行调试
- C安全编码--预处理
- c++作业2
- 值得阅读的C语言开源项目代码
- C语言中的指针和内存泄漏
- C语言实现泛型编程
- C语言实现多态
- C标准库<assert.h>实现
- 【poj 3009】Curling 2.0 中文题意&题解&代码(C++)
- 探索c++对象模型