RAII stands for Resource Acquisition Is Initialization, which you only need to remember for trivia night at your local C++ watering hole: it’s so far outgrown the acronym that the acronym itself has become misleading.
The original idea was that a constructor allowed you to initialize resources in the same moment they were acquired, getting rid of the old C-style “first you declare your variable, then you forget to initialize it, then you spend the rest of the day tracking down a hard-to-recreate bug brought on by whatever random pattern of bits was in memory there”. See? Resource acquisition is initialization. Your constructor initializes things on the spot, you never have to deal with this kind of bug.
But then we started looking at the flip side of it, and realized destructors were every bit as important as constructors. If we could guarantee object initialization through constructors, what about guaranteeing object cleanup through destructors?
Consider this bit of Python code:
What happens under garbage collection? The short answer is, we don’t know. Maybe, if we’re lucky, Python will run its garbage collector frequently enough that we’ll never exhaust our open file handles. Maybe if we’re unlucky Python will run its garbage collector infrequently enough that we exhaust our handles in a heartbeat. Although a good garbage collector guarantees our resources will be collected, few garbage collectors make any guarantees about when they will be collected: and that’s a problem for inherently limited resources like file handles, network sockets, database connections, and more.
On the other hand, consider what a proper C++ destructor can do:
Here, every time our while loop finishes the foo destructor gets called — which releases the megabyte of memory we acquired. This is essentially a very fast spin that never holds onto more than a megabyte of memory, with behavior guaranteed by the C++ standard.
RAII should really be called “predictable collection”, but it’s not. Sorry about that. But now you know what the hype is about and why modern C++ puts such an emphasis on, “if it’s a limited resource, wrap it in an object that has a proper destructor”.