正确的析构 静态实例和回收类
SingletonMode.cpp
#include <iostream> #include <pthread.h> class Singleton { private: Singleton(){ std::cout << "构造" << std::endl; }; ~Singleton() { std::cout << "析构" << std::endl; } public: static Singleton *getInstance() { static Singleton local_instance; return &local_instance; } }; class SingletonPattern { private: SingletonPattern() { std::cout << "创建单例模式对象!\n"; } SingletonPattern(const SingletonPattern& other); ~SingletonPattern() { } private: static SingletonPattern* m_Instance; static pthread_once_t ponce_; static void init() { m_Instance = new SingletonPattern(); } public: static SingletonPattern* GetInstance() { pthread_once(&ponce_, &SingletonPattern::init); return m_Instance; } void display() { std::cout << "使用单例模式!\n" ; } private: class CGabor { public: ~CGabor(){ if (SingletonPattern::m_Instance){ delete SingletonPattern::m_Instance; SingletonPattern::m_Instance = NULL; std::cout << "SingletonPattern 析构" << std::endl; } } }; static CGabor m_Gabor; }; SingletonPattern* SingletonPattern:: m_Instance = nullptr; SingletonPattern::CGabor SingletonPattern::m_Gabor; pthread_once_t SingletonPattern::ponce_ = PTHREAD_ONCE_INIT; // g++ SingletonMode.cpp -o SingletonMode -std=c++11 -lpthread int main() { Singleton *a = Singleton::getInstance(); Singleton *b = Singleton::getInstance(); if(a==b){ std::cout<< "a==b" <<'\n'; } SingletonPattern* m_Test = SingletonPattern::GetInstance(); m_Test->display(); return 0; }