Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1923063
  • 博文数量: 261
  • 博客积分: 8073
  • 博客等级: 中将
  • 技术积分: 2363
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-10 15:23
文章分类

全部博文(261)

文章存档

2013年(1)

2012年(1)

2011年(50)

2010年(34)

2009年(4)

2008年(17)

2007年(55)

2006年(99)

分类:

2011-05-17 09:23:50

创建单实例方法:
 
A:
 
class CSingleton
{
public:
    static CSingleton* Instance()
    {
        if ( 0 == m_pInstance )
        {
            m_pInstance = new CSingleton;
        }
 
        return m_pInstance;
    }
private:
    static CSingleton* m_pInstance
};
 
B:
 
class CSingleton
{
public:
    static CSingleton& Instance()
    {
        return m_instance;
    }
private:
    static CSingleton m_instance;
};
 
C:
class CSingleton
{
public:
    static CSingleton& Instance()
    {
        static CSingleton instance;
        return instance;
    }
};
 
方法B不可取,因为static变量初始化顺序不确定,造成static变量之间初始化依赖的问题。
 
方法A、C在多线程环境下会产生竞态,构造函数将被调用多次。
 
使用double lock Checking方法来实现单实例,可以参考
 
 
阅读(394) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~