标签:value opera dia aot shard let struct 循环 cpp
最近在写一个项目,其中用到好几个单例,类本身的设计不是很复杂,但是如果每个都写一遍单例又觉得有点冗余;所以查资料写了一个单例基类模板,只要一个类继承这个基类并且以自身作为模板参数就可以实现一个单例;关于单例本身的介绍在这里不重点介绍。
特点:
// bridf: a singleton base class offering an easy way to create singleton
#include <memory> // shard_ptr
#include <mutex>
#include <iostream>
template<typename T>
class Singleton{
typedef std::shared_ptr<T> Ptr;
protected:
Singleton() noexcept=default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
virtual ~Singleton() = default;
static Ptr instance_ptr;
static std::mutex singleton_mutex;
public:
static Ptr get_instance() noexcept(std::is_nothrow_constructible<T>::value)
{
if(instance_ptr==nullptr){
std::lock_guard<std::mutex> lk(singleton_mutex);
if(instance_ptr==nullptr){
instance_ptr = std::shared_ptr<T>(new T());
}
}
return instance_ptr;
}
};
template <typename T>
std::shared_ptr<T> Singleton<T>::instance_ptr=nullptr;
template <typename T>
std::mutex Singleton<T>::singleton_mutex;
/********************************************/
// Example:
// 1.friend class declaration is requiered!
// 2.constructor should be private
class DerivedSingle:public Singleton<DerivedSingle>{
// !!!! attention!!!
// needs to be friend in order to
// access the private constructor/destructor
friend class Singleton<DerivedSingle>;
int value;
public:
void info(){
std::cout<<"value: \n";
std::cout<<value<<std::endl;
}
void set_value(int i){
value = i;
}
int get_value(){
return value;
}
private:
DerivedSingle():value(0){}
DerivedSingle(const DerivedSingle&)=delete;
DerivedSingle& operator =(const DerivedSingle&)= delete;
};
int main(int argc, char* argv[]){
std::shared_ptr<DerivedSingle> instance = DerivedSingle::get_instance();
instance->info();
instance->set_value(1);
std::shared_ptr<DerivedSingle> instance2 = DerivedSingle::get_instance();
instance2->info();
return 0;
}
以上代码放在了 我的github中: https://github.com/sunchaothu/AdvancedCpp/tree/master/singleton
class DerivedSingle:public Singleton<DerivedSingle>;
Singleton
声明为友元;这样才能访问私有构造函数继承了这个类的代码不可以作为基类再被继承。
以上代码参考了以下链接;如果有纰漏之处,还请指正,以免误人子弟!
标签:value opera dia aot shard let struct 循环 cpp
原文地址:https://www.cnblogs.com/sunchaothu/p/10353507.html