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

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

问题描述

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

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

推荐答案

对于一个非常强大的概念来说,这是一个非常糟糕的名字,也许是 C++ 开发人员在切换到其他语言时错过的第一件事.有一些运动试图将这个概念重新命名为范围绑定资源管理,尽管它似乎还没有流行起来.

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.

当我们说资源"时,我们不仅仅指内存——它可以是文件句柄、网络套接字、数据库句柄、GDI 对象……简而言之,我们供应有限的东西,因此我们需要能够控制它们的使用.范围绑定"方面意味着对象的生命周期绑定到变量的范围,因此当变量超出范围时,析构函数将释放资源.一个非常有用的特性是它提供了更大的异常安全性.例如,比较这个:

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天全站免登陆