[問題] Singleton 與效率的問題
大家好 我幾乎沒在寫 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 因為會用不到)
這樣應該要怎麼實作會比較好呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.184.7.158
※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1416414040.A.18A.html
推
11/20 00:33, , 1F
11/20 00:33, 1F
→
11/20 01:14, , 2F
11/20 01:14, 2F
推
11/20 01:35, , 3F
11/20 01:35, 3F
→
11/20 01:57, , 4F
11/20 01:57, 4F
→
11/20 01:58, , 5F
11/20 01:58, 5F
→
11/20 01:58, , 6F
11/20 01:58, 6F
→
11/20 01:59, , 7F
11/20 01:59, 7F
→
11/20 07:27, , 8F
11/20 07:27, 8F
→
11/20 08:28, , 9F
11/20 08:28, 9F
→
11/20 08:28, , 10F
11/20 08:28, 10F
推
11/20 08:59, , 11F
11/20 08:59, 11F
→
11/20 08:59, , 12F
11/20 08:59, 12F
→
11/20 09:00, , 13F
11/20 09:00, 13F
→
11/20 09:00, , 14F
11/20 09:00, 14F
→
11/20 09:30, , 15F
11/20 09:30, 15F
推
11/20 10:38, , 16F
11/20 10:38, 16F
→
11/20 10:39, , 17F
11/20 10:39, 17F
→
11/20 10:41, , 18F
11/20 10:41, 18F
因為不同的地方之間是無法互相傳遞參數的 因此我才需要一個方法能夠取得同一物件
主要是在程式載入之後,會先執行 __attribute__((constructor)) 的函式
再執行 main()
這些函式需要取得同一物件,並把執行結果放入實體變數 dictionary/map 內。
※ 編輯: leondemon (125.227.48.32), 11/20/2014 12:00:57
→
11/20 12:16, , 19F
11/20 12:16, 19F
推
11/21 12:09, , 20F
11/21 12:09, 20F
→
11/21 12:09, , 21F
11/21 12:09, 21F
→
11/21 12:09, , 22F
11/21 12:09, 22F