标签:static thread stat initial class 开始 null std let
饿汉式声明, 一开始的时候对单例进行声明
#include <iostream> using namespace std; class Singleton{ public: static Singleton& getInstance(void){ return s_instance; } void print(void) { cout<<m_data<<endl; } private: Singleton(int data = 0):m_data(data){ cout << "单例被创建" << endl; }; Singleton(const Singleton&); int m_data; static Singleton s_instance; }; Singleton Singleton::s_instance = 123; int main(void){ Singleton& s1 = Singleton::getInstance(); Singleton& s2 = Singleton::getInstance(); Singleton& s3 = Singleton::getInstance(); cout << &s1 << endl; cout << &s2 << endl; cout << &s3 << endl; return 0; }
懒汉式声明, 在进行调用的时候进行声明,这里使用了线程里的互斥锁
#include <iostream> using namespace std; class Singleton{ public: static Singleton& getInstance(void){ pthread_mutex_lock(&mutex); if(s_instance == NULL){ s_instance = new Singleton(123); } ++s_count; pthread_mutex_unlock(&mutex); return *s_instance; } //所有的使用者都不用再销毁 void release(void) { pthread_mutex_lock(&mutex); if (--s_count == 0){ delete s_instance; s_instance = NULL; } pthread_mutex_unlock(&mutex); } //单列对象不用销毁 void print(void) { cout << m_data << endl; } private: Singleton(int data=0):m_data(data){ cout << "创建单例" << endl; } Singleton(const Singleton&); ~Singleton(void){ cout << "单例被删除" << endl; } int m_data; static Singleton* s_instance; static int s_count; static pthread_mutex_t mutex; }; Singleton* Singleton::s_instance = NULL;//进行私有化的生成操作 int Singleton::s_count = 0; //互斥锁定义和初始化 pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER; int main() { Singleton& s1 = Singleton::getInstance(); Singleton& s2 = Singleton::getInstance(); Singleton& s3 = Singleton::getInstance(); cout << "&s1" << &s1 << endl; cout << "&s2" << &s2 << endl; cout << "&s3" << &s3 << endl; s1.print(); s1.release(); s2.print(); s2.release(); s3.print(); s3.release(); }
C++-饿汉式声明(单例声明)和懒汉式声明(单例声明 线程thread)
标签:static thread stat initial class 开始 null std let
原文地址:https://www.cnblogs.com/hyq-lst/p/12866269.html