单例模式

懒汉模式

#include<iostream>
#include <type_traits>
#include <vector>
#include <memory>
#include <pthread.h>
using namespace std;



//线程安全的懒汉模式
class single {
public:
    static single* getsingle();

    void work() {

        cout << "work" << endl;
    }
private:
    static pthread_mutex_t mtx;
    static single* p;
    single() {
        pthread_mutex_init(&mtx, NULL);
    }
    single(single&) {}
    single& operator=(single&);
};
pthread_mutex_t single::mtx;
single* single::p = NULL;
single* single::getsingle() {
    if(p == NULL) {
        pthread_mutex_lock(&mtx);
        if(p == NULL) {
            p = new single();
        }
        pthread_mutex_unlock(&mtx);
    }
    return p;
}


int main() {
    single* a = single::getsingle();


    return 0;
}


饿汉模式

#include<iostream>
#include <vector>
#include <memory>
using namespace std;

//饿汉模式
class single {
public:
    static single* getsingle();
    void work() {
        cout << "work" << endl;
    }
private:
    static single* p;
    single() {}
    single(single&) {}
    single& operator=(single&);
};
single* single::p = new single();
single* single::getsingle() {
    return p;
}

int main() {
    single* a = single::getsingle();
    //以下的行为是可以的,因为是指针的拷贝,对象还是一个即 *a = *b;
    single* b = a;
    //以下的行为是不行的,因为是会拷贝出另外一个对象的
    single c = *a;
    return 0;
}

posted @ 2023-06-01 14:01  铜锣湾陈昊男  阅读(12)  评论(0)    收藏  举报