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 // ... };
obj
std::unique_ptr<>
std::shared_ptr
std::auto_ptr
- 3 回答
- 0 关注
- 854 浏览
添加回答
举报