我在多線程環境中創建單例類,任何線程都可以刪除單例對象。我想保護這一點。我在某處閱讀以避免這個問題,我們可以使析構函數爲私有,並可以提供一種銷燬方法。我們該怎麼做呢?示例代碼將有所幫助..如何在Singleton設計模式下使析構函數保密?
在此先感謝。
我在多線程環境中創建單例類,任何線程都可以刪除單例對象。我想保護這一點。我在某處閱讀以避免這個問題,我們可以使析構函數爲私有,並可以提供一種銷燬方法。我們該怎麼做呢?示例代碼將有所幫助..如何在Singleton設計模式下使析構函數保密?
在此先感謝。
使析構函數保持私有狀態並提供負責銷燬和清理單例的所有內存的Destroyer類。它將需要成爲Singleton類的朋友。爲了補充一點,你確定你絕對需要一個單身?或者這是另一種過度使用的情況?
class Singleton; // forward declaration
Singleton * s = NULL; // global object available to all threads
// Place this class in a location unavailable to all threads except Main thread
class ManageSingleton
{
public:
static void DestroySingleton(Singleton * s)
{
delete s;
}
}
class Singleton
{
friend class ManageSingleton;
protected:
~Singleton() {}
};
void main()
{
s = new Singleton;
while (...)
{
// other threads access Singleton object until program is finished
}
// Program is now finished; destroy Singleton object
ManageSingleton::DestroySingleton(s);
}
線程真的對這個設計有效,特別是如果你想要一個純粹的單身人士。你可以這樣想象它:
class t_singleton {
public:
static t_singleton& Get() {
/* thread safety is a consideration here: */
t_auto_ptr<t_singleton>& shared(Shared());
if (shared.isNull()) {
shared.setObject(new t_singleton);
}
/* and you should manage external references using another container type: */
return Shared().reference();
}
static void DestroyIt() {
/* thread safety is a consideration here: */
Shared().destroy();
}
private:
static t_auto_ptr<t_singleton>& Shared() {
static t_auto_ptr<t_singleton> s_Shared;
return s_Shared;
}
private:
t_singleton();
~t_singleton();
};
但這也應該建議許多線程與純單身人士的紅旗。
如果你真的想要擴展這個並強制執行一個純單例,你需要適當的引用計數容器 - 這表明單例對於這個問題是多種方式的不好的解決方案,並且會增加大量不必要的複雜性。祝你好運!
請勿使用單身人士。創建一個抽象類並傳遞一個子類的實例。 – 2012-04-17 07:00:09
簡單的解決方案不要給他們一個指針。給用戶一個參考,然後他們不允許刪除它。請參閱:http://stackoverflow.com/a/1008289/14065 – 2012-04-17 08:35:19