// // Created by 张衡 on 25-6-26. // #ifndef DL_H #define DL_H #include #include #include // class Single2 { // private: // Single2() { // }; // // Single2(const Single2 &) = delete; // // Single2 &operator=(const Single2 &) = delete; // // public: // ~Single2() { // std::cout << "~Single2()" << std::endl; // } // // static Single2 &GetInstance() { // // 线程安全 // static Single2 single; // return single; // } // }; // // class SingleOnceFlag { // public: // ~SingleOnceFlag() { std::cout << "~SingleOnceFlag()" << std::endl; } // // // static std::shared_ptr GetInst() { // // 复用 // static std::once_flag once_flag; // // 一个量,表示有无被call_once初始化 // std::call_once(once_flag, []() { // //初始化单例 // _instance = std::shared_ptr(new SingleOnceFlag()); // std::cout << "SingleOnceFlag()" << std::endl; // }); // return _instance; // } // // private: // static std::shared_ptr _instance; // // SingleOnceFlag() = default; // // SingleOnceFlag(const SingleOnceFlag &) = delete; // // SingleOnceFlag &operator=(const SingleOnceFlag &) = delete; // }; // class SingleNet; // class SafeDeletor // { // public: // void operator()(SingleNet *sf) // { // std::cout << "this is safe deleter operator()" << std::endl; // delete sf; // } // }; // // class SingleNet{ // public: // static std::shared_ptr getInstance(){ // static std::once_flag flag; // std::call_once(flag, []{ // _instance = std::shared_ptr(new SingleNet(), SafeDeletor()); // }); // return _instance; // } // // void PrintAddress() { // std::cout << _instance << std::endl; // } // //定义友元类,通过友元类调用该类析构函数 // friend class SafeDeletor; // private: // SingleNet() = default; // SingleNet(const SingleNet&) = delete; // SingleNet& operator=(const SingleNet& st) = delete; // ~SingleNet() { // std::cout << "this is singleton destruct" << std::endl; // } // static std::shared_ptr _instance; // // }; template class Singleton { protected: Singleton() = default; Singleton(const Singleton &) = delete; Singleton &operator=(const Singleton &) = delete; static std::shared_ptr _instance; public: ~Singleton() = default; static std::shared_ptr GetInst() { static std::once_flag flag; std::call_once(flag, [](){ _instance = std::shared_ptr(new T()); }); return _instance; } }; template std::shared_ptr Singleton::_instance = nullptr; class SingleNet : public Singleton { friend class Singleton; private: SingleNet() = default; public: ~SingleNet() { std::cout << "~SingleNet" << std::endl; } }; #endif // DL_H