我一直在尝试使用来自 STL 的一些 C++11 功能来实现单例。我阅读了一些实现,发现这非常好:http://silviuardelean.ro/2012/06/05/few-singleton-approaches/我做了一些更改并使下面的代码在 VS2013 上运行,但我仍然想知道:
a) 这个实现是线程安全的吗?
b) 从 GetInstance 返回 shared_ptr 而不是引用是否可以(良好做法)?
PS.: 我的单例被认为是一个 OpenGL 接口(interface)(这就是名字的原因)。
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)
{
}
最佳答案
我根本看不出在那里使用 shared_ptr
有什么意义。如果是单例,则不会复制。那么为什么要使用 shared_ptr
呢?
我也相信,Meyers 单例更容易实现,需要更少的输入,并且不依赖于动态分配,所以我想知道为什么有人会做其他事情。
尽管如此,我没有看到具体的线程问题。
关于C++单例实现STL线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34455574/