已关闭问题
面试问题求解答  (进入论坛模式)
提问者: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;
};
关闭所有答案回应    问题答案 ( 1 条 )
加油!学习了。。
回应该答案 (0)  |  回答者:zyq10086   |  2012-3-30 10:53