Re: [問題] 多型的自動回收

看板C_and_CPP (C/C++)作者 (火神)時間16年前 (2009/10/07 14:03), 編輯推噓3(308)
留言11則, 3人參與, 最新討論串6/13 (看更多)
你要不要試著用 aggregation class Base { public: Base( BaseInterface *entity) { content= entity; } void open() { content->doOpen(); } void close() { content->doClose(); } ~Base() { content->doClose(); delete content; } }; class BaseInterface { private: friend Base; virtual void doOpen()= 0; virtual void doClose()= 0; }; blah ※ 引述《legnaleurc (CA)》之銘言: : OK, 也許我描述得不夠清楚, 現在綜合兩篇的內容 : class Base { : public: : void open() { : // ... : this->doOpen(); : // ... : this->opening_ = true; : } : void close() { : // ... : this->doClose(); : // ... : this->opening_ = false; : } : virtual ~Base() { : // this->close(); : assert( !this->opening_ ); : } : private: : virtual void doOpen() = 0; : virtual void doClose() = 0; : bool opening_; : }; : class Derived { : virtual void doOpen() {} : virtual void doClose() {} : }; : ==== : 我就是希望在 Base 這個層級就能在解構時自動回收 : 但是礙於 destructor 內不能呼叫 virtual function : 目前我只有檢查 flag : 我只想問在這個狀況下有沒有比較好的做法 -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.124.99.126

10/07 14:17, , 1F
其實這要求超怪的都記得要 delete 了多個 close 有影響嗎
10/07 14:17, 1F

10/07 14:18, , 2F
除非你想把 Base 設計成 auto_ptr 的模式
10/07 14:18, 2F

10/07 14:44, , 3F
對 ... Base 永遠都會有 shared_ptr 包住 ...
10/07 14:44, 3F

10/07 14:46, , 4F
這個方法似乎可行,還可以順便把介面隱藏起來
10/07 14:46, 4F

10/07 15:46, , 5F
下面那個class名稱應該叫Impl不是叫Interface吧XD
10/07 15:46, 5F

10/07 15:46, , 6F
這看起來像是bridge pattern
10/07 15:46, 6F

10/07 15:49, , 7F
其實我名字是亂取的, 只強調它是 interface
10/07 15:49, 7F

10/07 15:50, , 8F
而且這樣寫... 目的完全跟 bridge 不同 =口=a
10/07 15:50, 8F

10/07 16:02, , 9F
咦..你這樣寫是要讓Derived繼承BaseInterface吧..
10/07 16:02, 9F

10/07 16:03, , 10F
還是兩個都要?要寫一個DerivedInterface和Derived..
10/07 16:03, 10F

10/07 16:03, , 11F
如果是後者 那樣只是讓情況複雜化了的感覺
10/07 16:03, 11F
文章代碼(AID): #1Ap2yPNw (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1Ap2yPNw (C_and_CPP)