3 回答
TA貢獻1876條經驗 獲得超6個贊
RawResourceHandle* handle=createNewResource();handle->performInvalidOperation(); // Oops, throws exception...deleteResource(handle); // oh dear, never gets called so the resource leaks
class ManagedResourceHandle {public:
ManagedResourceHandle(RawResourceHandle* rawHandle_) : rawHandle(rawHandle_) {};
~ManagedResourceHandle() {delete rawHandle; }
... // omitted operator*, etcprivate:
RawResourceHandle* rawHandle;};ManagedResourceHandle handle(createNewResource());handle->performInvalidOperation();TA貢獻1829條經驗 獲得超9個贊
將資源封裝到類中(其構造函數通常(但不一定是*)獲取資源,其析構函數總是釋放資源) 通過類的本地實例使用資源* 當對象超出作用域時,資源將自動釋放。
* 最新情況:
** UPDATE 2:
TA貢獻1802條經驗 獲得超5個贊
{
raii obj(acquire_resource());
// ...} // obj's dtor will call release_resource()class something {private:
raii obj_; // will live and die with instances of the class
// ... };objstd::unique_ptr<>std::shared_ptrstd::auto_ptr
- 3 回答
- 0 關注
- 940 瀏覽
添加回答
舉報
