这是一种创建基本单例对象的合法方式,它确保所有孩子都是单身人士吗?我想结合工厂模式使用它来确保所有因子都是单例。
关键类是为了防止孩子们攻击单例构造函数,但基本上只是一个形式参数。
这种方法特别有问题吗?
class singleton
{
protected:
struct key
{
private:
friend class singleton;
key(){}
};
public:
singleton(const key&)
{}
template <class child> static child* getInstance()
{
static key instanceKey;
static child* unique = new child(instanceKey);
return unique;
}
private:
};
class test : public singleton
{
public:
test(singleton::key& key)
: singleton(key)
{}
void init()
{
//init object
}
private:
};
int main()
{
test* t = singleton::getInstance<test>();
return 0;
}
答案 0 :(得分:0)
我添加了一个类来删除最后的所有工厂。 :) 您需要为此机制提供一系列虚拟析构函数。除此之外,我还没有发现其他内存泄漏,并且实例是唯一的。安全机制与&#39;键&#39;看起来也不错。我认为无法将手放在静态功能之外的键上。
#include <iostream>
#include <set>
class Singleton;
class Set_of_Singletons
{
friend class Singleton;
private:
std::set<Singleton*> instances;
Set_of_Singletons():instances(){}
public:
~Set_of_Singletons();
};
class Singleton
{
private:
static Set_of_Singletons children;
protected:
struct key
{
private:
friend class Singleton;
key(){}
};
public:
template <class Child> static Child* doNew()
{
static key instanceKey;
Child* u = new Child(instanceKey);
children.instances.insert((Singleton*)u);
return u;
}
template <class Child> static Child* getInstance()
{
static Child* unique = doNew<Child>();
return unique;
}
Singleton(const key&)
{}
virtual ~Singleton(){}
};
Set_of_Singletons::~Set_of_Singletons()
{
for (auto inst: instances)
delete inst;
instances.clear();
}
Set_of_Singletons Singleton::children;
class B: public Singleton
{
public:
B(Singleton::key& key)
: Singleton(key)
{
std::cout << ">>>> Construction of B \n";
}
virtual ~B()
{
std::cout << "<<<< Destruction of B \n";
}
};
class C final: public Singleton
{
public:
C(Singleton::key& key)
: Singleton(key)
{
std::cout << ">>>> Construction of C \n";
}
virtual ~C()
{
std::cout << "<<<< Destruction of C \n";
}
};
int main()
{
// Object creation seems all ok
B* x = Singleton::getInstance<B>();
std::cout << "x: " << x << "\n";
B* y = Singleton::getInstance<B>();
std::cout << "y: " << y << "\n";
C* v = Singleton::getInstance<C>();
std::cout << "v: " << v << "\n";
C* w = Singleton::getInstance<C>();
std::cout << "w: " << w << "\n";
return 0;
}
// ~Have fun.~
答案 1 :(得分:0)
你可以使用CRTP之类的东西:
template <typename T>
class Singleton
{
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static T& getInstance() {
static_assert(std::is_base_of<Singleton, T>::value, "T should inherit of Singleton");
static T instance;
return instance;
}
protected:
Singleton() = default;
~Singleton() = default;
};
然后
class MyFactory : Singleton<MyFactory>
{
private:
friend class Singleton<MyFactory>;
MyFactory() = default;
public:
//...
};