单例模板类
//单例模板类,C++11能保证函数中的静态成员线程安全
template <typename T>
class Singleton
{
T* value;
void create_singleton()
{
static T t;
value =&t;
}
public:
Singleton():value(){
create_singleton();
}
T* get_instance()
{
return value;
}
};
//要实现的单例类写法
class my_data
{
private :
my_data():i(0)
{
i+=rand();
}
int i;
public:
friend class Singleton<my_data>;
};
//测试
void test_singleton()
{
my_data* p =(Singleton<my_data>()).get_instance();
my_data* p2 ((Singleton<my_data>()).get_instance());
if(p == p2)
{
std::cout<<"same"<<std::endl;
}
}