方法一
将类的构造函数、析构函数权限设为protected,防止栈上生成对象提供两个静态成员函数,在该静态成员函数中完成对象的创建和销毁 #include <iostream> using namespace std; class HeapOnly { public: static HeapOnly* Create(){ return new HeapOnly; } static void Destory(HeapOnly* ptr){ delete ptr; ptr = nullptr; } protected: HeapOnly(){} HeapOnly(const HeapOnly&); //C++11写法 //HeapOnly(const HeapOnly&) = delete; ~HeapOnly(){} }; int main() { HeapOnly* object = HeapOnly::Create(); HeapOnly::Destory(object); return 0; }方法二
将构造函数权限设定为protected
#include <iostream> using namespace std; class HeapOnly { public: static HeapOnly* Create(){ return new HeapOnly; } protected: HeapOnly(){} HeapOnly(const HeapOnly&); //HeapOnly(const HeapOnly&) = delete; }; int main() { HeapOnly* object = HeapOnly::Create(); delete object; return 0; }方法三
将析构函数权限设定为protected
#include <iostream> using namespace std; class HeapOnly { public: static void Destory(HeapOnly* ptr){ delete ptr; ptr = nullptr; } protected: ~HeapOnly(){} }; int main() { HeapOnly* object = new HeapOnly; HeapOnly::Destory(object); return 0; }只在栈上创建对象
将operator new和operator delete权限设为private
#include <iostream> using namespace std; class StackOnly { public: StackOnly(){} ~StackOnly(){} private: void* operator new(size_t szie); void operator delete(void* ptr); }; int main() { StackOnly a; return 0; }一个类只能创建一个对象,保证系统中该类只有一个实例,并提供它的全局访问点,该实例被所有程序模块共享
饿汉模式
不管用不用,程序启动时就创建唯一的实例对象优点:简单缺点:可能导致程序进程启动慢,且如多有多个单例类对象实例启动顺序不确定 #include <iostream> using namespace std; class Singleton { public: static Singleton* GetInstance(){ return _instance; } private: Singleton(){} Singleton(const Singleton&); Singleton& operator=(Singleton const&); //Singleton(const Singleton&) = delete; //Singleton& operator = (Singleton const&) = delete; static Singleton* _instance; }; //在入口程序前完成单例对象的初始化 Singleton* Singleton::_instance = new Singleton; int main() { cout << Singleton::GetInstance << endl; cout << Singleton::GetInstance << endl; return 0; }懒汉模式
延迟加载优点:第一次使用是创建对象,进程启动无负载,多个单例实例启动顺序自由控制缺点:复杂 #include <iostream> #include <mutex> #include <thread> using namespace std; class Singleton { public: static Singleton* GetInstance(){ //使用Double-Check的方式加锁,保证效率和线程安全 if (_pInstance == nullptr){ _mtx.lock(); if (_pInstance == nullptr) _pInstance = new Singleton; _mtx.unlock(); } return _pInstance; } //实现一个垃圾回收类 class CGarbo{ public: ~CGarbo(){ if (Singleton::_pInstance) delete Singleton::_pInstance; } }; //定义一个静态成员变量,程序结束时系统自动调用它的析构函数,从而释放单例对象 static CGarbo Garbo; private: Singleton(){} Singleton(const Singleton&); Singleton& operator=(const Singleton&); static Singleton* _pInstance; static mutex _mtx; }; Singleton* Singleton::_pInstance = nullptr; Singleton::CGarbo Singleton::Garbo; mutex Singleton::_mtx; void func(int n){ cout << Singleton::GetInstance() << endl; } int main() { //多线程环境测试 thread t1(func, 10); thread t2(func, 10); t1.join(); t2.join(); cout << Singleton::GetInstance << endl; cout << Singleton::GetInstance << endl; return 0; }