logoalt Hacker News

quietbritishjim • today at 4:19 PM • 2 replies • view on HN

In C++ you can write "int x;" and get an object of type int.

If the only way to initialise a class-type object was to call some custom static method on it then you'd have to write "Foo x = Foo::create();". Suddenly it looks more special than a built-in type.


Replies

ninkendo • today at 4:41 PM

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.

➕ show 2 replies
pwdisswordfishq • today at 5:56 PM

But you can also write int x = rand(); how is that special?