c++单例模式总结
1 class Singleton 2 { 3 public: 4 static Singleton* Ins() 5 { 6 if (_ins == nullptr) 7 _ins = new Singleton(); 8 return _ins; 9 } 10 11 protected: 12 Singleton() {} 13 ~Singleton() {} 14 Singleton(const Singleton&) = delete; 15 Singleton& operator=(const Singleton&) = delete; 16 17 private: 18 static Singleton* _ins; 19 };
1 class Singleton 2 { 3 public: 4 ~Singleton() { std::cout << "destructor" << std::endl; } //必须声明为public 5 6 static std::shared_ptr<Singleton> Ins() 7 { 8 if (_ins == nullptr) 9 { 10 std::lock_guard<std::mutex> lock(_mt); 11 if (_ins == nullptr) 12 { 13 _ins = std::shared_ptr<Singleton>(new Singleton()); 14 } 15 } 16 return _ins; 17 } 18 19 Singleton(const Singleton&) = delete; 20 Singleton& operator=(const Singleton&) = delete; 21 22 protected: 23 Singleton() { std::cout << "constructor" << std::endl; } 24 25 private: 26 static std::shared_ptr<Singleton> _ins; 27 static std::mutex _mt; 28 };
1 class Singleton 2 { 3 public: 4 static Singleton& Ins() 5 { 6 static Singleton _ins; 7 return _ins; 8 } 9 10 Singleton(const Singleton&) = delete; 11 Singleton& operator=(const Singleton&) = delete; 12 13 protected: 14 Singleton() { std::cout << "constructor" << std::endl; } 15 ~Singleton() { std::cout << "destructor" << std::endl; } 16 };
1 class Singleton 2 { 3 public: 4 static Singleton* Ins() 5 { 6 std::call_once(_flag, []() { 7 _ins = new Singleton; 8 }); 9 return _ins; 10 } 11 12 Singleton(const Singleton&) = delete; 13 Singleton& operator=(const Singleton&) = delete; 14 15 protected: 16 Singleton() { std::cout << "constructor" << std::endl; } 17 ~Singleton() { std::cout << "destructor" << std::endl; } //必须声明为私有,否则返回指针将可析构 18 19 private: 20 struct Deleter 21 { 22 ~Deleter() { 23 delete _ins; 24 _ins = nullptr; 25 } 26 }; 27 static Deleter _deleter; 28 static Singleton* _ins; 29 static std::once_flag _flag; 30 }; 31 32 Singleton::Deleter Singleton::_deleter; 33 Singleton* Singleton::_ins = nullptr; 34 std::once_flag Singleton::_flag;
1 class Singleton 2 { 3 public: 4 static Singleton& Ins() 5 { 6 return _ins; 7 } 8 9 Singleton(const Singleton&) = delete; 10 Singleton& operator=(const Singleton&) = delete; 11 12 protected: 13 Singleton() { std::cout << "constructor" << std::endl; } 14 ~Singleton() { std::cout << "destructor" << std::endl; } 15 16 private: 17 static Singleton _ins; 18 }; 19 20 Singleton Singleton::_ins;
1 template<typename T> 2 class Singleton 3 { 4 public: 5 static T& Ins() 6 { 7 static T _ins; 8 return _ins; 9 } 10 11 protected: 12 Singleton() { std::cout << "constructor" << std::endl; } 13 ~Singleton() { std::cout << "destructor" << std::endl; } 14 Singleton(const Singleton&) = delete; 15 Singleton& operator=(const Singleton&) = delete; 16 }; 17 18 class AppInstance : public Singleton<AppInstance> 19 { 20 friend Singleton<AppInstance>; //声明友元 21 AppInstance() {} //必须私有化 22 ~AppInstance() {} 23 public: 24 void func() { std::cout << "func"<< std::endl; } 25 };
热门相关:冉冉心动 拒嫁豪门,前妻太抢手 今天也没变成玩偶呢 不科学御兽 异世修真邪君