스레드로부터 안전한 싱글 톤 싱글 톤의 디자인 패턴

방법 1 : Linux 스레드 라이브러리 pthread_once를 사용하여 달성하십시오.

복사 불가 .h

#pragma once

struct noncopyable
{
protected:
    noncopyable() = default;
    ~noncopyable() = default;
    
private:
    noncopyable(const noncopyable&) = delete;
    noncopyable& operator=(const noncopyable&) = delete;
};
#pragma once

#include "noncopyable.h"
#include <pthread.h>

template<typename T>
struct Singleton : noncopyable
{
    static T& getInstace()
    {
        pthread_once(&poncet_, &Singleton::init);
        return *data_;
    }

private:
    static void init()
    {
        data_ = new T();
    }

private:
    static T* data_;
    static pthread_once_t poncet_;
};

template<typename T>
T* Singleton<T>::data_ = nullptr;

template<typename T>
pthread_once_t Singleton<T>::poncet_ = PTHREAD_ONCE_INIT;

방법 2 : 내부 정적 지역 변수 사용

#pragma once

#include "noncopyable.h"

template<typename T>
struct Singleton : noncopyable
{
    static T& getInstace()
    {
        static T data_
        return data_;
    }

    // do somthing
};

사용하다:

#include <iostream>
#include "Singleton.h"

using namespace std;

struct Test
{
    Test() {}

    void doIt()
    {
        cout << "test do it" << endl;
    }
};

int main(int argc, char* argv[])
{
    auto& test = Singleton<Test>::getInstace();

    test.doIt();
    
    return 0;
}

 

추천

출처blog.csdn.net/xunye_dream/article/details/114792877