大家好 我幾乎沒在寫 C++ 算是個很新的新手
查了 C++ 的 Singleton 的作法 遇到了一些問題,想請教各位高手
這邊是 SO 的討論
http://stackoverflow.com/questions/1008019/c-singleton-design-pattern
於是我依樣話葫蘆 實作了以下 (綠色為新增的部分 黃色為引發問題的註解)
class A;
typedef std::map<std::string, A> DictA;
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// Dont forget to declare these two. You want to make sure they
// are unaccessable otherwise you may accidently get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
A a; // Compile Error 1
DictA _dict; // Compile Error 2
};
class A {
public:
A();
};
稍微研究一下 上面的 code 引發了兩個 compile error
Compile Error 1:
這部份需要把 class A 宣告搬到 class S 前面
似乎 forward declaration 不適用
想問一下一定需要把 class A 宣告在前面嗎?
Compile Error 2:
這不部分就不曉得為什麼引起 error
(implicit instantiation of undefined template)
似乎跟 Singleton 的實作有關 (static instance?)
最後想要問一個問題 我想做一個 singleton
並且有一個 dictionary(map) 可以高效率讀寫資料
最後這個 singleton 可在特定時間清除所有資料 (甚至 delete 因為會用不到)
這樣應該要怎麼實作會比較好呢?
作者:
yoco (眠月)
2014-11-20 01:35:00恩,假裝沒有這東西對你會有很多好處
那有什麼辦法可以在不同地方取得同一個物件呢?例如一個 global function=> getSharedInstance();然後可以在不需要時手動移除 releaseSharedInstance()我以為 Singleton pattern 在 C 應該是蠻常見的... 囧
作者:
Caesar08 (Caesar)
2014-11-20 07:27:00如果用A *a,就可以解決你的第一個問題
作者:
yoco (眠月)
2014-11-20 08:28:00error1: 對,要把定義移到前面。error2: 請問錯誤訊息是什麼?
他的error2是由error1引發的 修掉1應該就可以了另外Singleton在C並不常見,C幾乎都用Global Extern另外實作上Singleton我會建議直接用Loki就好Loki Singleton_Holder能解決絕大多數的問題
作者:
descent (「雄辯是銀,沉默是金」)
2014-11-20 09:30:00乾脆用 global variable 就好
在不同地方取得同一物件 → 用參數傳遞傳參數比較麻煩沒錯,但global state造成的麻煩更大但這件事真的要很有經驗才能理解它造成什麼麻煩
作者:
dirkc (3781615)
2014-11-20 12:16:00C++很常用的cout/cin即是用extern
我會思考不用 attribute 的方法不過你們的情況可能混合別人的code或是已經改不動那就真的沒辦法了