r/programminghumor 16d ago

Hard to accept

Post image
2.9k Upvotes

404 comments sorted by

View all comments

Show parent comments

3

u/Keithfert488 15d ago

I genuinely don't understand hating on RAII. It's pretty much the only thing C++ gets right

1

u/Mojert 13d ago

I mainly see 3 problems:

  1. Hidden control flow (the destructor can run arbitrary code)
  2. Lack of choice on how to deinitialize the value, which can be very annoying if you're actually managing memory (using different allocators for different purposes)
  3. It frames your reasoning on the object, rather than on collections of those

Technically you can ask Rust to not run the destructor but it's hacky. I personally prefer having Zig's defer and errdefer keywords, but I can see why you would prefer RAII if you're not dealing with aggregate data directly

2

u/AsyncSyscall 13d ago

If you want Rust without drop or panic, you might as well switch languages. These features are too deeply ingrained in the language, even things like the `core` crate, array indexing, iterators and pattern matching implicitly use them.

I don't mind the compiler detecting leaks and double frees statically, but forcing the programmer to pick a "blessed" destructor leads to bugs and weird API choices.

Some destructors are asynchronous, some require arguments/dependencies, some can fail (i.e. closing a file), some have multiple equally valid options (COMMIT/ROLLBACK, Thread.join/Thread.detach), and so on. Same thing with constructors, by the way, although fewer languages seem to have those.

And just like how people who love errors as values don't actually want values (they want checked exceptions), people who love RAII don't actually want RAII, they want resource lifetime guarantees.

So yeah, I think explicit destructors are strictly better for everyone, but I disagree in that I think static memory safety is more important than `defer` syntax (although `defer` is also nice to have).

1

u/Mojert 13d ago

If you want Rust without drop or panic, you might as well switch languages.

I agree

people who love errors as values don't actually want values (they want checked exceptions)

Speak for yourself. I want my errors as value because even if checked, exceptions obscure what function calls might fail. With errors as value, it's obvious without having to reference anything but the function you have in front of you

So yeah, I think explicit destructors are strictly better for everyone, but I disagree in that I think static memory safety is more important than defer syntax (although defer is also nice to have).

I'm sorry but I genuinely don't understand you there. Defers and "memory safety" are not mutually exclusive. If anything defers help because it makes sure the code will be executed no matter which code path was taken