[問題] Singleton 與效率的問題

看板C_and_CPP作者 (狗狗)時間9年前 (2014/11/20 00:20), 9年前編輯推噓5(5017)
留言22則, 8人參與, 最新討論串1/1
大家好 我幾乎沒在寫 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
是指Singleton嗎?
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
例如一個 global function=> getSharedInstance();
11/20 01:58, 5F

11/20 01:58, , 6F
然後可以在不需要時手動移除 releaseSharedInstance()
11/20 01:58, 6F

11/20 01:59, , 7F
我以為 Singleton pattern 在 C 應該是蠻常見的... 囧
11/20 01:59, 7F

11/20 07:27, , 8F
如果用A *a,就可以解決你的第一個問題
11/20 07:27, 8F

11/20 08:28, , 9F
error1: 對,要把定義移到前面。
11/20 08:28, 9F

11/20 08:28, , 10F
error2: 請問錯誤訊息是什麼?
11/20 08:28, 10F

11/20 08:59, , 11F
他的error2是由error1引發的 修掉1應該就可以了
11/20 08:59, 11F

11/20 08:59, , 12F
另外Singleton在C並不常見,C幾乎都用Global Extern
11/20 08:59, 12F

11/20 09:00, , 13F
另外實作上Singleton我會建議直接用Loki就好
11/20 09:00, 13F

11/20 09:00, , 14F
Loki Singleton_Holder能解決絕大多數的問題
11/20 09:00, 14F

11/20 09:30, , 15F
乾脆用 global variable 就好
11/20 09:30, 15F

11/20 10:38, , 16F
在不同地方取得同一物件 → 用參數傳遞
11/20 10:38, 16F

11/20 10:39, , 17F
傳參數比較麻煩沒錯,但global state造成的麻煩更大
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
C++很常用的cout/cin即是用extern
11/20 12:16, 19F

11/21 12:09, , 20F
我會思考不用 attribute 的方法
11/21 12:09, 20F

11/21 12:09, , 21F
不過你們的情況可能混合別人的code或是已經改不動
11/21 12:09, 21F

11/21 12:09, , 22F
那就真的沒辦法了
11/21 12:09, 22F
文章代碼(AID): #1KRCDO6A (C_and_CPP)