jeudi 24 décembre 2015

c++ singleton implementation STL thread safe

I've been trying to implement a singleton with some C++11 features from STL. I read about a few implementations and I found this pretty good: http://ift.tt/1IBLW72 I made a few changes and got the bellow code working on VS2013, but I still would like to know:

a) Is this implementation thread-safe?

b) Is it ok (good practice) to return a shared_ptr from GetInstance instead of a reference?

PS.: My singleton is ment to be an OpenGL interface (that's the reason for the name).

HandlerOpenGL.h

#pragma once



// STL headers
#include <memory> // shared_ptr
#include <mutex> // once_flag



// OpenGL Handler Singleton
class HandlerOpenGL
{
public:
    // Constructor/Destructor interface
    static std::shared_ptr<HandlerOpenGL> GetInstance(void);    // Only way to access singleton
    ~HandlerOpenGL(void);
    HandlerOpenGL(const HandlerOpenGL&) = delete;   // Avoid any copy/move
    HandlerOpenGL(HandlerOpenGL&&) = delete;
    HandlerOpenGL& operator=(const HandlerOpenGL&) = delete;
    HandlerOpenGL& operator=(HandlerOpenGL&&) = delete;

private:
    // Hide construction method/variables
    HandlerOpenGL(void);    // Private to be created once
    static std::shared_ptr<HandlerOpenGL> _instance;
    static std::once_flag _flag;
};

HandlerOpenGL.cpp

// Own header
#include "HandlerOpenGL.h"
// STL headers
#include <memory> // shared_ptr, make_shared
#include <mutex> // once_flag, call_once



// instanciate static members
std::shared_ptr<HandlerOpenGL> HandlerOpenGL::_instance(nullptr);
std::once_flag HandlerOpenGL::_flag;



std::shared_ptr<HandlerOpenGL> HandlerOpenGL::GetInstance(void)
{
    std::call_once(_flag, [](){ _instance.reset(new HandlerOpenGL); });
    return _instance;
}



HandlerOpenGL::~HandlerOpenGL(void)
{
}



HandlerOpenGL::HandlerOpenGL(void)
{
}

Aucun commentaire:

Enregistrer un commentaire