CPP 单例模式和缺陷
03 Mar 2014实现一个单例模式
class Singleton {
private:
Singleton() { cout << "Singleton::constructor" << endl; }
~Singlton() { cout << "Singleton::destructor" << endl; }
Singleton(const Singleton&) {};
Singleton &operator=(const Singleton&) {};
public:
static Singleton* getInstance() {
if(m_aInstance == NULL) {
m_aInstance = new Singleton();
}
return m_aInstance;
}
void show() {
cout << "Singleton::show" << endl;
}
private:
static Singleton* m_aInstance;
};
Singleton* Singleton::m_aInstance = NULL;
int main(int argc, char **argv) {
Singleton* aSingleton = Singleton::getInstance();
aSingleton->show();
return 0;
}
Singleton::constructor
Singleton::show
系统会自动调用在栈和静态数据区上分配的对象的析构函数来释放资源。
修改程序如下:
class Singleton {
private:
Singleton() { cout << "Singleton::constructor" << endl; }
~Singleton() { cout << "Singleton::destructor" << endl; }
Singleton(const Singleton&) {};
Singleton &operator=(const Singleton&) {};
public:
static Singleton* getInstance() {
if(m_aInstance == NULL) {
m_aInstance = new Singleton();
}
return m_aInstance;
}
void show() {
cout << "Singleton::show" << endl;
}
private:
class Garbage{
public:
~Garbage() {
if(m_aInstance != NULL) {
delete m_aInstance;
}
}
};
private:
static Singleton* m_aInstance;
static Garbage m_garbage;
};
Singleton* Singleton::m_aInstance = NULL;
Singleton::Garbage Singleton::m_garbage;
int main(int argc, char **argv) {
Singleton* aSingleton = Singleton::getInstance();
aSingleton->show();
return 0;
}
Singleton::constructor
Singleton::show
Singleton::destructor
我们看到Singleton::destructor被明确的执行了。