Hacker News new | ask | show | jobs
by ncruces 266 days ago
Rust mandates that every field in a user-defined type is initialized at once. How do you propose to retrofit that into C without "constructors"?
1 comments

C has had designated initializers since C99, if you want you can initialise every struct field at once.
I encourage you to read (at least) this section of this blog before making simplistic suggestions: https://thephd.dev/just-put-raii-in-c-bro-please-bro-just-on...

How do you mandate initialization, handle copies, move objects, prevent double frees? What's RAII without any of that?

You mandate it like you mandate anything else in C. You don't.

You pick C because you want a language that doesn't require a variable to be initialised before mutably referencing it, and you write your defer statements or "destructors" defensively, expecting that a variable could be in any state when it comes time to dispose of it.

Or if you find that unacceptable, you accept that C isn't the language you want. There's many other choices available.

There's no way to write a "destructor" defensively, if the contents of memory it is trying to "destroy" are undefined.

Whereas it's perfectly possible to only defer a statement when you know the "object" has been properly initialized.

That's why defer makes sense in a language like C (even Go), but RAII does not.

I agree with everything you've said, except the conclusion: C can't add proper safe RAII, but being "proper and safe" is not a threshold C even tries to uphold.
But would a destructor that runs automagically when a value goes out of scope, even if it's not properly initialized (and with zero regards for copies or moves) be in any way better than a defer that's explicitly called after it is initialized?

Cause, like, that's the entire thread.