[問題] C++同類別創建不同物件資源共享問題(解決)

看板C_and_CPP (C/C++)作者時間11年前 (2014/09/24 00:10), 11年前編輯推噓2(207)
留言9則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 6 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) N/A 問題(Question): 我現在需要提供一Library給多執行緒程式,Library的實作有包含其它類別的物件 預期使用API創建不同的物件應該為資源獨立 但實際去跑才發現同類別的二個物件,其底層使用的其它物件是同一份 例如: // Library的header class Lib_Impl; // Library的實作類別 class Lib { public: Lib(void) {}; void set_id(int obj_id); .... private: Lib_Impl *m_impl; }; // Library的cpp檔 Lib::Lib() { m_impl = new Lib_Impl(); } void Lib::set_id(int obj_id) { m_impl->obj_id = obj_id; } 假如Lib_Impl有個成員變數為obj_id,Library提供一API去設定它 如果使用者create 2個Lib物件並設定不同的id 例如: // 使用此Library的cpp檔 void main() { // Create Library object Lib *obj_1 = new Lib(); Lib *obj_2 = new Lib(); obj_1->set_id(1); obj_2->set_id(2); } 此時我預期二個物件底下Lib_Impl的id應該是不一樣的 但obj_1底下的id都會被obj_2所影響 請問是哪裡出錯了呢? 此Library的設計方式如果在多執行緒的環境創建多個物件會是安全的嗎? 謝謝 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): 謝謝johnpage網友, 我回去檢查Lib_Impl類別, 因為它是用工廠方法創建的 而我把二個可能創建的類別宣告成全域物件才會導致這個問題 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.201.12.247 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1411488622.A.0C4.html

09/24 00:41, , 1F
只看這樣似乎沒看到什麼問題, 有沒有實際的程式?
09/24 00:41, 1F

09/24 01:23, , 2F
有static member嗎?
09/24 01:23, 2F

09/24 03:35, , 3F
header file 和 cpp 裡重複定義 construcor?
09/24 03:35, 3F

09/24 03:35, , 4F
如果 Library.cpp 有 include Library.h compile 應該會出錯
09/24 03:35, 4F

09/24 03:36, , 5F
但是如果 .cpp 沒 include .h, 只重寫一次 class body
09/24 03:36, 5F

09/24 03:36, , 6F
main.cpp 在 compile 的時候可能把 .h 裡的空 constructor
09/24 03:36, 6F

09/24 03:37, , 7F
inline, 那 m_impl 就沒有被 new 到 obj_1/2 的 m_impl 都指
09/24 03:37, 7F

09/24 03:38, , 8F
到 0, 在某些系統下還是可以讀寫 obj_id 而且會是同一份
09/24 03:38, 8F

09/24 08:09, , 9F
問題應該在 class Lib_Impl
09/24 08:09, 9F
※ 編輯: imalex (210.201.12.247), 09/24/2014 22:25:39
文章代碼(AID): #1K8Pjk34 (C_and_CPP)
文章代碼(AID): #1K8Pjk34 (C_and_CPP)