术语“资源获取”的含义是初始化 [英] The meaning of the term - Resource Acquisition Is Initialization

查看:261
本文介绍了术语“资源获取”的含义是初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道RAII是什么。

I know what RAII does. It is all about preventing memory leaks etc. when/if a code throws an exception.

现在,我想了解一下 smart 的含义。 > term。
http://en.wikipedia.org/wiki/Acquisition

Now, I wish to understand the meaning of that smart term. http://en.wikipedia.org/wiki/Acquisition

获取意味着获取某物。

Acquisition means acquiring something.

因此,当我们说 资源获取是初始化 时,这是什么意思?

我只是在谈这个术语的含义,而不是一般的概念。

So, when we say that resource acquiring is initialization, what does that mean?
I am just talking about the meaning of the term here, not about the concept in general.

推荐答案

之前(可能是斯科特·迈尔斯,我不记得了),RAII应该被称为破坏是资源释放,或这样的话。

It has been said before (possibly by Scott Meyers, I can't remember), that RAII should be called "Destruction is resource release", or words to that effect.

什么资源获取是初始化字面意思是当一个对象被构造(初始化)时,它获取一些资源(例如内存分配或锁)。换句话说,它说你应该只通过 获取一个资源。

What "resource acquisition is initialization" literally means is that when an object is constructed (initialized), it acquires some resource (such as a memory allocation or a lock). In other words, it says you should only ever acquire a resource, by initializing some object whose destructor will release it.

这是非常重要的,因为它偏离了C编码风格,你通过某种特定API提供的方式获取资源(例如 malloc() accept() pthread_mutex_lock()),并通过显式调用相应的函数c> free(), close() pthread_mutex_unlock())。在C ++中存在异常使得这种方法相当不可行。即使在C中,也会导致一些繁琐的代码,每次使用API​​都必须写出来,每个用户都必须确保控件在使用资源后始终通过该代码。

This is important to stress because it's a departure from C coding style, where you acquire resources by whatever means a particular API provides (for example malloc(), accept(), or pthread_mutex_lock()), and release them by explicitly calling the corresponding function (for example free(), close(), pthread_mutex_unlock()). The presence of exceptions in C++ makes this approach fairly unworkable. Even in C it results in some tedious code that every use of the API has to write out, and every user has to ensure that control always passes through that code after they're finished using the resource.

但是模式的重要部分是当对象被销毁时,它释放该资源。实际上,无论是通过初始化对象还是通过在对象初始化之后执行其他操作来获取资源都没有关系。并且当存在生成由RAII对象管理的资源的初始化之外的操作时,人们仍然将对象引用为RAII对象。

But the important part of the pattern is that when the object is destroyed, it releases that resource. It doesn't actually matter whether you acquire the resource by initializing the object, or by doing something else with the object after it has been initialized. And people will still refer to an object as a "RAII object" when there are operations other than initialization that generate the resource(s) managed by the RAII object.

,不要太担心RAII中的获取是初始化,因为无论如何它有点误导。

So, don't worry too much about the "acquisition is initialization" in "RAII", because anyway it's slightly misleading.

这篇关于术语“资源获取”的含义是初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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