You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.1 KiB

5 years ago
#ifndef SINGLETON_DCLP_HPP
#define SINGLETON_DCLP_HPP
#include <mutex>
template<typename T>
class Singleton_DCLP
{
public:
Singleton_DCLP() {};
virtual ~Singleton_DCLP()
{
if (m_instance)
delete m_instance;
};
Singleton_DCLP( const Singleton_DCLP& ) = delete;
Singleton_DCLP& operator=( const Singleton_DCLP& ) = delete;
/** I knowthat c++-11 has the "atomic initializers" and this can be
* replaced with:
*
* static T getInstance()
* {
* static Singleton instance;
* return instance;
* }
*
* But that is not supported in Visual Studio 2012 SP4
* https://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/
*/
static T* getInstance()
{
if (!m_instance) {
std::lock_guard<std::mutex> guard(m_lock);
if (!m_instance) {
volatile T *temp = new T();
m_instance = (T*)temp;
}
}
return (T*)m_instance;
}
private:
static std::mutex m_lock;
static volatile T* m_instance;
};
template<class T> std::mutex Singleton_DCLP<T>::m_lock;
template<class T> volatile T* Singleton_DCLP<T>::m_instance = 0;
#endif // SINGLETON_DCLP_HPP