c ++单例实现STL线程安全 [英] c++ singleton implementation STL thread safe
问题描述
我一直在尝试使用STL的某些C ++ 11功能来实现单例.我了解了一些实现,并发现它非常不错: http://silviuardelean .ro/2012/06/05/few-singleton-approaches/我进行了一些更改,使波纹管代码在VS2013上正常工作,但我仍然想知道:
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://silviuardelean.ro/2012/06/05/few-singleton-approaches/ I made a few changes and got the bellow code working on VS2013, but I still would like to know:
a)此实现是线程安全的吗?
a) Is this implementation thread-safe?
b)可以(从习惯上)从GetInstance返回shared_ptr而不是引用吗?
b) Is it ok (good practice) to return a shared_ptr from GetInstance instead of a reference?
PS .:我的单例是OpenGL接口(这就是这个名称的原因).
PS.: My singleton is ment to be an OpenGL interface (that's the reason for the name).
HandlerOpenGL.h
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
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
?
I do not see a point of using shared_ptr
there at all. If it is a singleton, it will not be copied. So why use shared_ptr
?
我还相信,Meyers单例操作起来非常容易,需要更少的键入,并且不依赖于动态分配,所以我想知道为什么有人还会做其他事情.
I also believe, a Meyers singleton is so much easier to do, requires less typing, and doesn't rely on dynamic allocation, so I wonder why would anybody would do anything else.
尽管如此,我没有看到与此相关的特定线程问题.
Despite all this, I do not see a specific threading issues with that.
这篇关于c ++单例实现STL线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!