单例模式
下面是恶汉式(推介):
class singlePerson{
private:
singlePerson()
{
}
public:
static singlePerson *getInstance()
{
return m_instance;
}
void myshow()
{
cout << "我是恶汉子,我饥不择食\n";
}
~singlePerson()
{
cout << "析构函数\n";
}
private:
static singlePerson*m_instance;
};
singlePerson* singlePerson::m_instance = new singlePerson;
void main()
{
singlePerson *p1 = singlePerson::getInstance();
singlePerson *p2 = singlePerson::getInstance();
if (p1 == p2)
{
cout << "succeed\n";
p1->myshow();
}
else
{
cout << "fail\n";
}
system("pause");
}
结果:
我们可以看到这里没有执行析构函数,如果在类中分配了其它资源就会造成内存泄漏。解决方法1.手动调用
static void freememroy()
{
delete m_instance;
}
调用方式:
singlePerson::freememroy();
结果:
2.智能指针:
class singlePerson{
private:
singlePerson()
{
}
char *ptr = new char[20];
public:
static shared_ptr<singlePerson> getInstance()
{
return m_instance;
}
void myshow()
{
cout << "我是恶汉子,我饥不择食\n";
}
~singlePerson()
{
delete[]ptr;
cout << "析构函数\n";
}
private:
static std::shared_ptr<singlePerson> m_instance;
};
std::shared_ptr<singlePerson> singlePerson::m_instance(new singlePerson);
void play()
{
shared_ptr<singlePerson> p = singlePerson::getInstance();
p->myshow();
}
void main()
{
play();
cout << "hello world\n";
system("pause");
}
结果:
最推介的懒汉方式:
class singleTy{
private:
singleTy()
{
cout << "构造函数\n";
}
~singleTy()
{
cout << "析构函数\n";
}
public:
static singleTy &getinstance()
{
static singleTy t;
return t;
}
void showmsg()
{
cout << "hello Ty\n";
}
};
void play()
{
singleTy &t = singleTy::getinstance();
t.showmsg();
singleTy &t1 = singleTy::getinstance();
t1.showmsg();
}
void main()
{
play();
cout << "hello world\n";
system("pause");
}
结果:
在多线程中如果变量在初始化的时候,并发同时进入声明语句,并发线程将会阻塞等待初始化结束。,所以具有线程安全性。