josefx 1 day ago

> Note that in C++, reading from a variable before writing to it is undefined behavior, so it's not particularly clear what benefit you're getting from this.

The compiler cannot always tell if a variable will be written to before it is accessed. if you have a 100kb network buffer and you call int read = opaque_read(buffer); the compiler cannot tell how much or if anything at all was written to buffer and how size relates to it, it would be forced to initialize every byte in it to zero. A programmer can read the API docs, see that only the first read bytes are valid and use the buffer without ever touching anything uninitialized. Now add in that you can pass mutable pointers and references to nearly anything in C++ and the compiler has a much harder time to tell if it has to initialize arguments passed to functions or if the function is doing the initialization for it.

1
tialaramex 1 day ago

In C++ 26 you will be able to specifically mark that you want the initialization not to happen, whereupon of course (a) your reviewers can see this and critique it, are you sure it doesn't need initializing? Isn't this the code we run once per month that doesn't need to be fast or small? (b) the maintenance programmer coming later can identify that you did it on purpose and consider whether it's still correct

The problem was never "This is always a bad idea" and instead only "This is usually a bad idea so you should need to explicitly ask for it when you want it, so that when somebody writes it by mistake they can be told about that".

Rust chooses to need a lot of ceremony to make a MaybeUninit, and especially to then assume_init with no justification because it's not actually initialized - but that's because almost nobody who wants to write that understands what will actually happen, they typically have the C programmer "All the world's a PDP-11" understanding and in that world this operation has well understood and maybe even desirable behaviour. We do not live in that world, this is not a PDP-11 and it isn't shy about that. The thing they want is called a "freeze semantic" and it's difficult to ensure on modern systems.

But if you hate the ceremony, regardless of the fact there's a good reason for it - many languages have less ceremony, often just a handful of keystrokes to say "Don't initialize this" will be enough to achieve what you intended. What they don't do, which C++ did, was just assume the fact you forgot to write an initializer means you want the consequences - when in reality it usually means you're just human and make mistakes.