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

39 lines
946 B
C++

#pragma once
#include <memory>
#include <mutex>
#include <utility> // for std::forward
template<typename T>
class Singleton {
public:
template<typename ...Args>
static T* GetInstance(Args&&... args) {
if (!m_instance) {
std::call_once(m_onceFlag, [] {
m_instance.reset(new T(std::forward<Args>(args)...));
});
}
return m_instance.get();
}
protected:
Singleton() = default;
virtual ~Singleton() = default;
private:
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
private:
static std::unique_ptr<T> m_instance;
static std::once_flag m_onceFlag;
};
template<typename T>
std::unique_ptr<T> Singleton<T>::m_instance;
template<typename T>
std::once_flag Singleton<T>::m_onceFlag;