您的位置:首页 > 编程语言 > C语言/C++

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)

{

//

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: