简介
GetLeakySingleton是单例模板类,线程安全的
GetLeakySingleton
cpp
template <typename T> class GetLeakySingleton {
public:
static butil::subtle::AtomicWord g_leaky_singleton_untyped;
static pthread_once_t g_create_leaky_singleton_once;
static void create_leaky_singleton();
};
包含三个静态成员
g_leaky_singleton_untyped:存放分配后的地址
g_create_leaky_singleton_once:创建时保证只调用一次
create_leaky_singleton:创建实例的方法
初始化
cpp
template <typename T>
butil::subtle::AtomicWord GetLeakySingleton<T>::g_leaky_singleton_untyped = 0;
template <typename T>
pthread_once_t GetLeakySingleton<T>::g_create_leaky_singleton_once = PTHREAD_ONCE_INIT;
创建单例
cpp
template <typename T>
void GetLeakySingleton<T>::create_leaky_singleton() {
T* obj = new T;
butil::subtle::Release_Store(
&g_leaky_singleton_untyped,
reinterpret_cast<butil::subtle::AtomicWord>(obj));
}
创建单例的模板方法
cpp
template <typename T>
inline T* get_leaky_singleton() {
const butil::subtle::AtomicWord value = butil::subtle::Acquire_Load(
&GetLeakySingleton<T>::g_leaky_singleton_untyped);
if (value) {
return reinterpret_cast<T*>(value);
}
pthread_once(&GetLeakySingleton<T>::g_create_leaky_singleton_once,
GetLeakySingleton<T>::create_leaky_singleton);
return reinterpret_cast<T*>(
GetLeakySingleton<T>::g_leaky_singleton_untyped);
}