有人能确认一下这是否是一个线程安全的单例实现吗?

can some one confirm if this is a thread safe implementation of singleton

本文关键字:安全 线程 单例 一个 实现 确认 一下 是否是      更新时间:2023-10-16
#include "iostream"
#include "atomic"
using namespace std;
class Singleton
{
    Singleton();

    static Singleton * _pInstance;
    public:
       ~Singleton() {
       }
       static Singleton* getInstance() {
          Singleton * tmp = _pInstance;
          atomic_thread_fence(std::memory_order_acquire);
          if (tmp == nullptr){
             tmp = _pInstance;
             if (!tmp) {
                _pInstance = new Singleton();
                atomic_thread_fence(std::memory_order_release);
                _pInstance = tmp;
             }
         return _pInstance;
     }
};
Singleton* Singleton::_pInstance = nullptr;

你的实现似乎是线程安全的,但最简单的方法,使一个线程安全的单例看起来像

class Singleton {
    Singleton();
public:
    ~Singleton() {
    }
    static Singleton* getInstance() {
        static Singleton theInstance;
        return &theInstance;
    }
};

或者最好返回一个引用

    static Singleton& getInstance() {
        static Singleton theInstance;
        return theInstance;
    }
你不需要在这里重新发明轮子。