Inherit Singleton
Inherit Singleton
快速问题。是否有继承singleton以使子类成为singleton的方法?我到处搜索过,但我能找到的每个单例都是按类实现的,而不是以通用的方式实现的。
是的,有一种通用的方法。您可以通过CRTP实现Singleton,例如:
template<typename T>
class Singleton
{
protected:
Singleton() noexcept = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
virtual ~Singleton() = default; // to silence base class Singleton<T> has a
// non-virtual destructor [-Weffc++]
public:
static T& get_instance() noexcept(std::is_nothrow_constructible<T>::value)
{
// Guaranteed to be destroyed.
// Instantiated on first use.
// Thread safe in C++11
static T instance{};
return instance;
}
};
然后从中派生,让你的孩子成为单身汉:
class MySingleton: public Singleton<MySingleton>
{
// needs to be friend in order to
// access the private constructor/destructor
friend class Singleton<MySingleton>;
public:
// Declare all public members here
private:
MySingleton()
{
// Implement the constructor here
}
~MySingleton()
{
// Implement the destructor here
}
};
在Coliru上直播
singleton有一个静态getInstance()
方法,该方法在第一次调用时创建该类的单个实例,因此静态绑定到正在实例化的singleton类的类型。我看不出拥有辛格尔顿层次结构的直接效用。但是,如果您坚持要有一个方法,您可以考虑将getInstance
方法设置为virtual
,并在扩展父Singleton的类中重写它。
class Singleton {
public virtual Singleton * getInstance() const
{
// instantiate Singleton if necessary
// return pointer to instance
}
...
};
class MySingleton : public Singleton {
// overrides Singelton's getInstance
public virtual MySingleton * getInstance() const
{
// instantiate MySingleton if necessary
// return pointer to instance
}
};
当然,一个健壮的实现将存储并返回智能指针。
相关文章:
- C++ Singleton - Prevent ::instance() to variable
- Singleton ofstram:已创建但未写入的文件
- XCode 警告"此处需要实例化变量'Singleton:<Foo>:_instance',但没有可用的定义
- C++Singleton实例禁用重新调用
- 没有从Singleton到嵌套Listener*的可行转换
- 禁止复制构造函数和赋值运算符singleton类
- Singleton模式中的手动析构函数调用:调用多次
- 如何将Singleton类信号连接到MainWindow类插槽或方法
- Helgrind 报告了使用 Singleton 及其构造函数之间可能存在的竞争
- 关于std::cout,为什么使用"extern"比"singleton pattern"
- 'inherit class'中类型 'template class' 引用的初始化无效
- 静态库中只有一个C 11 Singleton的实例
- Forward宣布了Singleton班级,并带有Freshial声明的朋友功能
- 对Singleton的未定义引用::实例
- Singleton with template
- 在用户类中包括PYBIND11嵌入式模块的正确方法(作为Singleton类的一部分)是什么?
- Singleton和不同的库版本
- 具有多个非默认构造函数基的Singleton派生类
- Singleton实现:与Singleton类相比,名称空间方法通常更可取吗
- Inherit Singleton