亚星游戏官网-yaxin222

门户 | 手机客户端 | 论坛 | 人才 | 百科 | 搜索 | 技术问答 | English
已关闭问题
面试问题求解答
提问者:septanwonder   |  提问时间:2012-3-29 09:08
周四去某企业面试,被问道C++的单例模式的实现,现场手写,我写了一个返回函数局部静态对象的例程, 然后就被鄙视了。。。 然后回家google,原来那种写法不是线程安全的,重新写了一遍,求拍砖。 C/C++ code class CSingeton { private: class CAssist { public: CAssist(void) { m_lock = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER; if (NULL == mp_inst) { pthread_mutex_lock(&m_lock); if (NULL == mp_inst) { mp_inst = new CSingeton(); } pthread_mutex_unlock(&m_lock); } } ~CAssist(void) { if (NULL != mp_inst) { delete mp_inst; mp_inst = NULL; } } CSingeton *mp_inst; pthread_mutex_t m_lock; }; public: static CSingeton &GetInst(void) { static CAssist sm_assist; return *sm_assist.mp_inst; } void PrintX(void) const { cout << m_x << endl; } private: CSingeton(void) : m_x(33) { cout << "singleton constructed" << endl; } ~CSingeton(void) { cout << "singleton destructed" << endl; } CSingeton(CSingeton const &r); CSingeton &operator =(CSingeton const &r); int m_x; };
加油!学习了。。
回答时间:2012-3-30 10:53
 
我要回应:  回应字数在5000字以内

 

XML 地图 | Sitemap 地图