3 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超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貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個贊
將資源封裝到類中(其構(gòu)造函數(shù)通常(但不一定是*)獲取資源,其析構(gòu)函數(shù)總是釋放資源) 通過類的本地實(shí)例使用資源* 當(dāng)對象超出作用域時,資源將自動釋放。
*
最新情況:
**
UPDATE 2:

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超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 // ... };
obj
std::unique_ptr<>
std::shared_ptr
std::auto_ptr
- 3 回答
- 0 關(guān)注
- 912 瀏覽
添加回答
舉報