C++: 单例模式和缺陷
实现一个单例模式3 | Singleton() { cout << "Singleton::constructor" << endl; } |
4 | ~Singlton() { cout << "Singleton::destructor" << endl; } |
5 | Singleton( const Singleton&) {}; |
6 | Singleton &operator=( const Singleton&) {}; |
8 | static Singleton* getInstance() { |
9 | if (m_aInstance == NULL) { |
10 | m_aInstance = new Singleton(); |
15 | cout << "Singleton::show" << endl; |
18 | static Singleton* m_aInstance; |
21 | Singleton* Singleton::m_aInstance =NULL; |
23 | int main( int argc, char **argv) { |
24 | Singleton* aSingleton = Singleton::getInstance(); |
编译执行上面的代码,输出如下:
Singleton::constructor
Singleton::show
我们发现上面的输出并没有调用到Singleton的虚构函数,Singleton的资源可能没有被释放。现在的问题是要怎么才能在程序退出的时候正确释放Singleton的资源。我们注意到这样一个事实:
系统会自动调用在栈和静态数据区上分配的对象的析构函数来释放资源。
修改程序如下:
3 | Singleton() { cout << "Singleton::constructor" << endl; } |
4 | ~Singleton() { cout << "Singleton::destructor" << endl; } |
5 | Singleton( const Singleton&) {}; |
6 | Singleton &operator=( const Singleton&) {}; |
8 | static Singleton* getInstance() { |
9 | if (m_aInstance == NULL) { |
10 | m_aInstance = new Singleton(); |
15 | cout << "Singleton::show" << endl; |
22 | if (m_aInstance != NULL) { |
29 | static Singleton* m_aInstance; |
30 | static Garbage m_garbage; |
33 | Singleton* Singleton::m_aInstance =NULL; |
34 | Singleton::Garbage Singleton::m_garbage; |
36 | int main( int argc, char **argv) { |
37 | Singleton* aSingleton = Singleton::getInstance(); |
编译上面的代码并执行,输出如下:
Singleton::constructor
Singleton::showSingleton::destructor
我们看到Singleton::destructor被明确的执行了。
相关阅读:
递归模板实现单例模式