单例模式C++实现

发布时间 2023-11-13 12:02:56作者: 云中锦书来
局部静态变量实现懒汉单例模式 ``` //更简单的线程安全初始化 #include using namespace std; class SingleObject{ private: SingleObject(){std::cout << "Singleton instance created." << std::endl;}; public: static SingleObject& get_instance(){ static SingleObject instance;//局部静态变量实现单例模式 return instance; //非静态成员是不存在,是无法返回实例的 } void show_message(); }; int main(){ cout << "---------主线程开始---------" << endl; SingleObject& my_instance = SingleObject::get_instance(); my_instance.show_message(); cout << "---------主线程结束---------" << endl; return 0; } void SingleObject::show_message(){ cout << "完成了单例模式" << endl; } ```
饿汉式单例模式 ``` #include using namespace std; /* 饿汉式单例模式 */ class SingleObject{ private: static SingleObject instance; SingleObject(){std::cout << "Singleton instance created." << std::endl;}; public: static SingleObject get_instance(){ return instance; //非静态成员是不存在,是无法返回实例的 } void show_message(); }; int main(){ cout << "---------主线程开始---------" << endl; SingleObject::get_instance().show_message(); cout << "---------主线程结束---------" << endl; return 0; } void SingleObject::show_message(){ cout << "完成了单例模式" << endl; } ```