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

看板C_and_CPP (C/C++)作者 (雅古蟹)時間16年前 (2009/10/07 05:39), 編輯推噓0(002)
留言2則, 1人參與, 最新討論串5/13 (看更多)
你要不要嘗試著使用auto_ptr? 我是說,如果你把你要用的資源,包裝在一個Resource物件裡面。當這個Resource物件被 destroy的時候,會自動地把資源釋放。那,你的Base就會很簡單. class Base { public: void open() { initResource(); } protected: virtual void initResource() { if (!resourcePtr) resourcePtr = auto_ptr<Resource>(new Resource); } auto_ptr<Resource> resourcePtr; }; class Derived : public Base {}; 當你的Derived物件要被解構時,會先解構resourcePtr。如果resourcePtr有指向任何R esource物件,該物件的destructor會被呼叫。這樣子你的Base或Derived根本不用寫 destructor. 如果真的需要close()的話,把resourcePtr歸零就好了,歸零時,auto_ptr會先自動解構原 先指向的物件。 class Base { public: void open() { initResource(); } void close() { destroyResource(); } protected: virtual void initResource() { if (!resourcePtr) resourcePtr = auto_ptr<Resource>(new Resource); } virtual void destroyResource() { resourcePtr = auto_ptr<Resource>; } auto_ptr<Resource> resourcePtr; }; 你的Derived, 如果有其他資源要管理的話, 也是放在auto_ptr裡面,然後請記得 overwrite initResource()和destroyResource(), 確保新增的資源. 假設Derived要管理一項新的資源Resouce2. class Derived : public Base { protected: virtual void initResource() { if (!resourcePtr) resourcePtr = auto_ptr<Resource>(new Resource); if (!resource2Ptr) resource2Ptr = auto_ptr<Resource2>(new Resource2); } virtual void destroyResource() { resourcePtr = auto_ptr<Resource>; resource2Ptr = auto_ptr<Resource2>; } auto_ptr<Resource2> resource2Ptr; }; 我記得這樣子應該是沒錯吧,請您試一試。 ※ 引述《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: 86.9.120.242

10/07 13:55, , 1F
我無法定出 Resource 的介面,所以無法用這種方式
10/07 13:55, 1F

10/07 13:55, , 2F
強迫 subclasses 遵守
10/07 13:55, 2F
文章代碼(AID): #1AoxaSB- (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1AoxaSB- (C_and_CPP)