c++单例模式的自动释放问题
1.嵌套类+静态对象
#include <iostream>
using std::cout;
using std::endl;
class Singleton
{
public:
static Singleton * getInstance()
{
//使用懒汉模式时,在多线程环境下是非线程安全的
//可以通过加锁来实现线程安全
if(nullptr == _pInstance) {
_pInstance = new Singleton();
}
return _pInstance;
}
private:
class AutoRelease
{
public:
AutoRelease() {
cout << "AutoRelease()" << endl; }
~AutoRelease()
{
if(_pInstance) {
delete _pInstance;
cout << "~AutoRelease()" << endl;