c++单例模式

来源:互联网 发布:dreamweaver 替代软件 编辑:程序博客网 时间:2024/06/12 01:40

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)
{
//
}

}

0 0
原创粉丝点击