单例模式为什么只被构造一次
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模式
[解决办法]
static GridSingleton* getInstance() { if (_instance == NULL) { boost::mutex::scoped_lock socped_l(_mtx); if (_instance == NULL) { _instance = new GridSingleton(); } } return _instance; }