资源获取是什么意思是初始化(RAII)? [英] What is meant by Resource Acquisition is Initialization (RAII)?

查看:273
本文介绍了资源获取是什么意思是初始化(RAII)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

资源获取是什么意思是初始化(RAII)?

What is meant by Resource Acquisition is Initialization (RAII)?

推荐答案

这是一个非常可怕的名字, ,并且可能是C ++开发人员在切换到其他语言时错过的1个事情之一。有一个运动,试图重命名这个概念为范围绑定资源管理,虽然它似乎还没有抓住到目前为止。

It's a really terrible name for an incredibly powerful concept, and perhaps one of the number 1 things that C++ developers miss when they switch to other languages. There has been a bit of a movement to try to rename this concept as Scope-Bound Resource Management, though it doesn't seem to have caught on just yet.

当我们说'Resource'时,我们不只是意味着内存 - 它可以是文件句柄,网络套接字,数据库句柄,GDI对象...总之,我们有一个有限的供应,因此我们需要能够控制他们的使用。 'Scope-bound'方法意味着对象的生命周期被绑定到变量的范围,因此当变量超出范围时,析构函数将释放资源。这是一个非常有用的属性,它使更大的异常安全。例如,比较:

When we say 'Resource' we don't just mean memory - it could be file handles, network sockets, database handles, GDI objects... In short, things that we have a finite supply of and so we need to be able to control their usage. The 'Scope-bound' aspect means that the lifetime of the object is bound to the scope of a variable, so when the variable goes out of scope then the destructor will release the resource. A very useful property of this is that it makes for greater exception-safety. For instance, compare this:

RawResourceHandle* handle=createNewResource();
handle->performInvalidOperation();  // Oops, throws exception
...
deleteResource(handle); // oh dear, never gets called so the resource leaks

使用RAII一个

class ManagedResourceHandle {
public:
   ManagedResourceHandle(RawResourceHandle* rawHandle_) : rawHandle(rawHandle_) {};
   ~ManagedResourceHandle() {delete rawHandle; }
   ... // omitted operator*, etc
private:
   RawResourceHandle* rawHandle;
};

ManagedResourceHandle handle(createNewResource());
handle->performInvalidOperation();

在后一种情况下,当异常被抛出并且堆栈被解开时,局部变量被销毁这可确保我们的资源得到清理,不会泄漏。

In this latter case, when the exception is thrown and the stack is unwound, the local variables are destroyed which ensures that our resource is cleaned up and doesn't leak.

这篇关于资源获取是什么意思是初始化(RAII)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆