What makes a language unwilling/incapable to incorporate RAII?

109 views Asked by At

I live in a C and C++ bubble. Anything I've ever written that involves over a couple hundred lines has always been in those two languages.

I hear around everywhere that RAII is (for the most part) a unique idiom to C++. But why is that exactly? I believe most OOP languages force you to create objects on the heap (by all means correct me if I'm wrong), which then leads to wanting a GC to deal with memory management altogether. But what's wrong/bad just having stuff work from the stack in the first place? What advantage does it serve implementing things as they do?

Perhaps this extends to the lack of understanding I have behind heap usage in the first place. I don't quite 'get' the point of it outside of precaching big stuff before it's needed. 99.9% of my code ever involving pointers at all is just interfacing with old code!

2

There are 2 answers

0
U2EF1 On

Python (and almost any other reference counted language) also has de facto RAII. If something runs out of references when it runs out of scope, it gets collected. The problem with C++'s method safety-wise is that if anything gets saved after the scope exits, if you haven't done something special, it destroys itself then-and-there.

This can be eased a little by using smart-pointers, any of various idioms, and by "being really careful"; the point is that it isn't automatically safe, so other languages don't tend to use it. For an example of a language that's trying really hard for RAII and safety, take a look at Rust. They're doing a fantastic job of, essentially, verifying these smart-pointers and idioms and carefulness at compile time to have the best of both worlds.

And then other languages have various "context manager" constructs that are similar, but it's not nearly the scale of C++ where everything's a context manager.

0
Columbo On

I hear around everywhere that RAII is (for the most part) a unique idiom to C++.

Because most other high-level languages either don't support it directly or encourage you to use something else. Java is a well-known example, finalize is rarely used. C++ is the language to promote RAII as it's focussed on performance and needs exception safety and reasonable resource management at the same time.

RAII doesn't have anything to do with heap storage primarily. It designates the idiom of using constructors and destructors to initialize and destroy ressources or data together with an object that owns those resources. In that sense it also defines ownership by binding resources to an object and its lifetime.

But what's wrong/bad just having stuff work from the stack in the first place?

What if you have 100MiB of data? Certainly that can't go on the 8MiB stack. The stack is concepted for small and easily cache-able data. E.g. fundamental types and basic compound types thereof, but not large arrays. Perhaps your programs are not working with vast amounts of data yet.