The meaning of the term "Resource Initialization"

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

Now I want to understand the meaning of this smart term. http://en.wikipedia.org/wiki/Acquisition

Acquisition means acquiring something.

So, when we say that resource search is initialization , what does it mean?
I'm just talking about the meaning of the term here, and not about the concept at all.

+4
source share
2 answers

It was said earlier (probably, Scott Myers, I don’t remember) that RAII should be called “Destruction is the release of resources” or words in this regard.

“Initialization of the acquisition of resources” literally means that when an object is created (initialized), it acquires some resource (for example, memory allocation or locking). In other words, it says that you should ever acquire a resource by initializing some object whose destructor will release it.

This is important to emphasize, because this is a departure from the C-coding style, where you acquire resources by any means provided by a specific API (for example, malloc() , accept() or pthread_mutex_lock() ) and release them explicitly by calling the corresponding function (for example, free() , close() , pthread_mutex_unlock() ). The presence of exceptions in C ++ makes this approach rather inoperative. Even in C, this leads to some tedious code that every use of the API must write out, and each user must ensure that control always passes through this code after they are finished using the resource.

But the important part of the template is that when an object is destroyed, it frees this resource. It doesn't really matter if you acquire the resource by initializing the object, or by doing something else with the object after its initialization. And people will treat the object as an RAII object when there are operations other than initialization that generate resources (resources) controlled by the RAII object.

So, don’t worry about “initializing the acquisition” in “RAII”, because in any case it is a little misleading.

+9
source

Acquisition is a general term, but it always refers to an operation that allocates a certain resource - for example, a file descriptor, a database connection, a mutex, ... - specifically to your code that "owns" it, and therefore should be released when it does not need to avoid a resource leak.

An important concept with RAII is that the resource of the resource is tied to the lifetime of the owner object, since the acquisition coincides with initialization (= creation of the object) and release with its destruction (which is guaranteed).

0
source

All Articles