源自Boost最优雅的C++单例模式
一、Boost Thread库
Boost功能非常强大,在此借鉴一下其线程库中的单例源码,线程安全且优雅。
二、singleton.hpp
#pragma once
template<class T>
class singleton: private T
{
public:
static T& instance()
{
static singleton<T> inst;
return inst;
}
};
#define INSTANCE(class_name) singleton<class_name>::instance()
三、测试示例
#include "singleton.hpp"
#include <stdio.h>
class Demo
{
public:
void test() { printf("test\n");}
};
int main()
{
INSTANCE(Demo).test();
return 0;
}