c++ 单例模式
线程安全
#include <iostream> #include <process.h> #include <windows.h> using namespace std; class Singelton { private: static Singelton *single; public: static Singelton *GetSingelton(); void print_addr() { printf("%d\n", single); } ~Singelton() { printf("deconstructor singleton\n"); } }; Singelton *Singelton::single = new Singelton; Singelton *Singelton::GetSingelton() { return single; } int main() { Singelton *test = Singelton::GetSingelton(); test->print_addr(); Singelton *test1 = Singelton::GetSingelton(); test1->print_addr(); system("pause"); return 0; }
非线程安全
#include <iostream> #include <process.h> #include <windows.h> using namespace std; class Singelton { private: static Singelton *single; public: static Singelton *GetSingelton(); void print_addr() { printf("%d\n", single); } ~Singelton() { printf("deconstructor singleton\n"); } }; Singelton *Singelton::single = nullptr; Singelton *Singelton::GetSingelton() { if (single == nullptr) { single = new Singelton; } return single; } int main() { Singelton *test = Singelton::GetSingelton(); test->print_addr(); Singelton *test1 = Singelton::GetSingelton(); test1->print_addr(); system("pause"); return 0; }