首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

单例模式为何只被构造一次

2012-08-21 
单例模式为什么只被构造一次class Singleton{private:int teststatic Singleton *instanceSingleton(){c

单例模式为什么只被构造一次
class Singleton
{
private:
int test;
static Singleton *instance;
Singleton(){cout<<"new"<<endl;test=0;}
~Singleton(){cout<<"delete"<<endl;}

public:
static Singleton *GetInstance()
{
static Singleton singleton;
return &singleton;
}
void setvalue(int v) { test=v; }
int getvalue() { return test; }
};

int main()  
{
Singleton *single1=Singleton::GetInstance();
Singleton *single2=Singleton::GetInstance();

cout<<"value 1:"<<single1->getvalue()<<endl;
single1->setvalue(100);
cout<<"value 2:"<<single2->getvalue()<<endl;

if (single2==single1)
{
cout<<"single1 == single2"<<endl;
}
return 0;
}

输出结果是:
new//调用两次GetInstance ,那为什么只调用了一次构造函数呢?  
value1 :0
value2 :100
single1=single2
delete

[解决办法]
在工作代码中如果这样写Singleton,应该是不行的。至少在GetInstance函数中要判断一下instance这个指针是否有效,然后再决定是否调用私有构造函数。

参考:
C++实现Singleton模式
[解决办法]

探讨

在工作代码中如果这样写Singleton,应该是不行的。至少在GetInstance函数中要判断一下instance这个指针是否有效,然后再决定是否调用私有构造函数。

参考:
C++实现Singleton模式

[解决办法]
那是饿汉单例 懒汉单例是要判断的
C/C++ code
        static GridSingleton* getInstance()    {        if (_instance == NULL)        {            boost::mutex::scoped_lock socped_l(_mtx);            if (_instance == NULL)            {                _instance = new GridSingleton();            }        }        return _instance;    } 

热点排行