I know what RAII does. It is all about preventing memory leaks etc. when/if a code throws an exception.
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.
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.
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.
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.
So, don't worry too much about the "acquisition is initialization" in "RAII", because anyway it's slightly misleading.
Acquisition is a generic term, but it refers always to an operation that allocates some resource - e.g. a file handle, a database connection, a mutex, ... - specifically to your code, which "owns" it, and thus must be released when it's not needed to avoid leaking resources.
The important concept with RAII is that the resource lifetime is bound to the lifetime of the owner object, because the acquisition coincides with the initialization (=creation of the object), and the release with its destruction (which is guaranteed).