1. 单例模式
1)类构造函数私有化
2)拷贝构造、拷贝复制删除
3)使用静态类对象、静态类指针#include<iostream> #include <thread> #include <mutex> #include <string> class Log_1 { private: Log_1() {}; public: Log_1& operator= (const Log_1& log1) = delete; Log_1(const Log_1& log1) = delete; static Log_1& getInstance() { static Log_1 log1; return log1; } void print(const std::string& str) { std::cout << __TIME__ << " " << str << std::endl; } }; class Log_2 { private: Log_2(){}; public: Log_2(const Log_2& log) = delete; Log_2& operator= (const Log_2& log2) = delete; static Log_2& getInstance() { static Log_2* log2 = nullptr; if (!log2) log2 = new Log_2; return *log2; } void print(const std::string& str){ std::cout << __TIME__ << " " << str << std::endl; } }; void func() { Log_2::getInstance().print("error_2"); } int main () { // Log_1::getInstance().print("error_1"); //懒汉模式 // Log_2::getInstance().print("error_2"); //饿汉模式 std::thread t1(func); std::thread t2(func); t1.join(); t2.join(); }