logoalt Hacker News

ninkendo • today at 4:41 PM • 3 replies • view on HN

In C++, `int x;` leaves the int uninitialized, which isn't really constructing at all. In rust (which I program in lately so I'll use it as the example) you simply can't use uninitialized variables in the first place without unsafe code, so the equivalent would either be:

  let x: i32;
  foo(x); // compiler error
or if you really wanted to use uninitialized memory,

  let x: i32 = unsafe { std::mem::uninitialized() }; // compiler warning
  foo(x);
which, in rust, can be done with any other type too (substitute i32 for any T and the above examples are identical.) I don't see anything different about built-in types here vs standard ones, other than the compiler has literals for the built-ins, which is more a consequence of rust not allowing literals for library types. But that's a very different discussion.

I guess the argument might be that for C++, they want the author of the type to determine whether the value should be left uninitialized on declaration/construction, instead of the caller. Which is... not exactly the semantics I would have chosen.


Replies

steveklabnik • today at 7:13 PM

Please note that mem::uninitialized is always unsound. Your example should be using MaybeUninit<T>. While that example would still be unsound directly anyway, it at least gives you the ability to do the right thing (foo would need to take the MaybeUninit<i32>).

pjmlp • today at 5:37 PM

It is up to the constructor to only initialize storage, or do whatever it feels like to have values assigned to it.

Thus a default constructor replicates a plain int x;, whereas the copy constructor or single value constructor is used for int x = 42;.

By the way, already in the 16 bit days you could configure to have warnings as errors for variables being used without initialisation.

➕ show 1 reply
quietbritishjim • today at 5:06 PM

Hmm interesting. Is there a way to "value initialise" (in C++ speak) an int in Rust to set it to zero? Like `let x: i32 = {};` (without explicitly writing `=0`)? How about a way to do that for a sort of plain struct where there are multiple members you just want to set to their default values?

➕ show 2 replies