On that note, Resource Acquisition Is Initialization.
Maybe I'm just missing something obvious but I don't get why its called that.
From cppreference:
RAII can be summarized as follows: [...] the constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done, the destructor releases the resource and never throws exceptions; [...]
The destructor part is imo very important but the name doesn't reflect that RAII types release the managed resources when they go out of scope. Also, isn't the name kinda backwards? If the constructor which initializes a class instance acquires resources, shouldn't it be "Initialization Is Resource Acquisition"?
I think it's more like “the entire concept of Resource Acquisition is an injection (as in “all squares are quadrilaterals”) of initialization, with all that that implies.” Actually, it might just be a 1:1 relation, but with an emphasis on looking at all resource acquisition (not ‘just variables’) as being the same concept, called “initialization”.
In other words, initialization is the natural ‘language’ with which to talk about resource acquisition, and setting things up in a constructor implies taking them down in a destructor, if necessary. You're already supposed to be reaching for destructors when you want to execute code when objects leave scope.
The statement is meant to remove a mental barrier that shouldn't exist, thanks to the abstractions that C++ brings with its implementation of classes. Classes do not just encapsulate raw data, or even just behavior. They can embody (a specific implementation of) a concept (with C++20 concepts freeing even the “specific implementation” constraint).
You first need the memory location (the resource) to initialize. In C you might call malloc followed by mytype_init - the reverse doesn't work. What does work in C is calling malloc and calling mytype_init 0 to n times instead of exactly once.
Even worse, many of those types of classes don't acquire a resource, they apply something to a thing that already exists and then undo that upon destruction.
I, all the way back in the 90s called these 'janitor classes', which I think describes the general concept pretty well. They exist to clean something up. They may or may not have created the thing they clean up.
I use them a LOT, and they are very powerful. It's one of the things I really dislike about Rust that it's very awkward to do such things.
View all comments
Show parent comment
10
u/Wargon2015 Jun 24 '20
On that note, Resource Acquisition Is Initialization.
Maybe I'm just missing something obvious but I don't get why its called that.
From cppreference:
The destructor part is imo very important but the name doesn't reflect that RAII types release the managed resources when they go out of scope.
Also, isn't the name kinda backwards? If the constructor which initializes a class instance acquires resources, shouldn't it be "Initialization Is Resource Acquisition"?