ClickHouse/base/ext/singleton.h

45 lines
704 B
C++
Raw Normal View History

2020-01-16 12:37:29 +00:00
#pragma once
#include <memory>
namespace ext
{
/** Thread-unsafe singleton. It works simply like a global variable.
* Supports deinitialization.
*
* In most of the cases, you don't need this class.
* Use "Meyers Singleton" instead: static T & instance() { static T x; return x; }
*/
2020-01-22 15:20:19 +00:00
2020-01-16 12:37:29 +00:00
template <class T>
2020-02-03 17:06:59 +00:00
class Singleton
2020-01-16 12:37:29 +00:00
{
public:
2020-02-03 17:06:59 +00:00
Singleton()
2020-01-16 12:37:29 +00:00
{
2020-02-03 17:06:59 +00:00
if (!instance)
instance = std::make_unique<T>();
2020-01-16 12:37:29 +00:00
}
T * operator->()
{
return instance.get();
}
static bool isInitialized()
{
2020-02-03 17:06:59 +00:00
return !!instance;
}
static void reset()
{
instance.reset();
}
2020-01-16 12:37:29 +00:00
private:
inline static std::unique_ptr<T> instance{};
};
2020-01-22 15:20:19 +00:00
}