Hacker News new | ask | show | jobs
by masklinn 4480 days ago
> it seems like it really means "stack variables that go out of scope are deallocated"

And the destructor, if any, is called. That means you can bundle automatic cleanup action in the destructor, no need for goto: cleanup, @try/@finally or some other sort of "manual" cleanup, the cleanup is implicitly set up by, well, the setup.

The ability itself is by no means unique to C++ (even amongst oldies, Smalltalk has BlockClosure#ensure: and Common Lisp has unwind-protect) but a surprising number of languages still don't have such a capability, and it's a pretty neat consequence of C++'s memory model.

1 comments

> And the destructor, if any, is called

Right, that's implied by a C++ object being deallocated. I understand how it works - it's just that it's really obvious if you know anything at all about how the stack works (and C++ destructors).

> it's just that it's really obvious if you know anything at all about how the stack works (and C++ destructors).

Which does not change it being an elegant solution to the problem of resource scoping does it?

Also the semantics of C++ destructor (and their relation to stack deallocation) had to be defined to get RAII, and it was, back in the very early 80s when the idea of resource scoping was not exactly well known.

It's using automatic storage duration and destructors tow age dynamically allocated memory (or some other resource which require manual management.). So yeah, that's it.
The "non obvious" part that makes it RAII is simply that the stack variable in question owns another resource besides itself. The stack variable is being used to wrap something else, be it a chunk of memory, a file handle, one or more other dynamically allocated objects, etc. The key in RAII is that when the stack variable wrapper goes out of scope, the wrapped resource (which is in addition to the stack variable) is deallocated, freed, released, etc.