1、构造函数为私有,只有类内的代码可以调用构造函数,禁止主函数创建对象。
2、static President p;那一行放在instance()里面。若把 p 当做类的静态数据成员,会出现调用instance()时还没有定义 p 的情况。
在全局区域创建单例
class President
{
string name = "yych";
President(){}
President(const President& a);//不允许复制
President& operator=(const President& a)const;//不允许赋值
public:
static President& instance()
{
static President p;
return p;
}
void setname(const string &s)
{
name = s;
}
string getname()
{
return name;
}
};
在堆中创建单例(智能指针)
class CSingleton
{
private:
CSingleton() //构造函数是私有的
{
}
static shared_ptr<CSingleton> m_pInstance;
public:
static CSingleton * GetInstance()
{
if (m_pInstance == NULL) //判断是否第一次调用
m_pInstance = shared_ptr<CSingleton>(new CSingleton());
return m_pInstance.get();
}
};
shared_ptr<CSingleton> CSingleton::m_pInstance = nullptr;
在堆中创建单例(普通指针)
class CSingleton
{
public:
~CSingleton(){ cout << "~CSingleton" << endl; }
class CGarbo // 它的唯一工作就是在析构函数中删除CSingleton的实例
{
public:
CGarbo()
{
cout << "CGarbo" << endl;
}
~CGarbo()
{
cout << "~CGarbo" << endl;
if (CSingleton::m_pInstance)
{
cout << "delete" << endl;
delete CSingleton::m_pInstance;
CSingleton::m_pInstance = NULL;
}
}
};
static CGarbo Garbo; // 定义一个静态成员,在程序结束时,系统会调用它的析构函数
static CSingleton * instance()
{
if (m_pInstance == NULL)
m_pInstance = new CSingleton();
return m_pInstance;
}
static CSingleton * m_pInstance;
private:
CSingleton() { cout << "CSingleton" << endl; };
};
CSingleton* CSingleton::m_pInstance = NULL;
CSingleton::CGarbo CSingleton::Garbo;