[英]A base singleton object in C++
這是一種創建基本單例對象的合法方式,它確保所有它的子單元也是單例嗎? 我想結合工廠模式使用它來確保所有因子都是單例。
關鍵類是為了防止孩子們攻擊單例構造函數,但基本上只是一個形式參數。
這種方法特別有問題嗎?
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;
}
我添加了一個類來刪除最后的所有工廠。 :)你需要為這種機制提供一系列虛擬析構函數。 除此之外,我還沒有發現其他內存泄漏,並且實例是唯一的。 帶有“密鑰”的安全機制似乎也很好。 我認為無法將手放在靜態功能之外的鍵上。
#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.~
你可以使用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:
//...
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.