【发布时间】:2018-06-10 17:11:54
【问题描述】:
我正在尝试为我的子类实现一个简单的继承单例模式。 因此,我正在实现一个父类,并且因为我想让其他人尽可能轻松地创建一个新的 Singleton 子类,我需要在父类构造函数中处理子类的 Singleton 实现所需的所有操作类。
#include <vector>
#include <typeinfo>
#include <iostream>
class Father
{
protected:
Father()
{
for(auto & instance : Father::singletonInstances)
if(typeid(instance) == typeid(this)) // typeid(this) will always be "Father", which is actually the issue
{
// Singleton instance already exists for this class
* this = instance;
std::cout<<"An instance of the given class is already active\n";
return;
}
std::cout<<"Constructed\n";
// Otherwise, mark this as the Singleton instance for this class
Father::singletonInstances.emplace_back(this);
}
public:
Father operator=(Father * inputObj) { return * inputObj; }
private:
static std::vector<Father *> singletonInstances;
};
std::vector<Father *> Father::singletonInstances;
class Child : protected Father
{
public:
Child() : Father() {}
};
class Child2 : protected Father
{
public:
Child2() : Father() {}
};
int main()
{
new Child();
new Child2();
return 0;
}
输出:
Constructed
An instance of the given class is already active
所以,再把事情说清楚: - 问题是 typeid(this) 在构造函数中始终是“父亲” - 新的孩子();新的 Child2();应该被允许 - 新的孩子();新的孩子();不应该被允许 - 不应对子类进行任何修改
我知道我的 Singleton 实现可能看起来很奇怪。我乐于接受新想法。
我能够在 JScript 中实现这些想法,但在 C++ 中我似乎无法找到使其工作的方法。
【问题讨论】:
标签: c++ oop inheritance singleton