Remix.run Logo
▲ pjmlp a day ago

Because in languages like C++ and Swift, contrary to your other examples, the goal is that library types should be able to do everything that built-in types expose.

Thus you need all mechanisms to implement the same capabilities, thus constructors, by the way they are not alone in this approach.

▲aw1621107 a day ago | parent | next [-]

That feels a bit like begging the question? Library types only need constructors to replicate built-in types if built-in types use constructors themselves. But do built-in types need constructors? What is lost by just using regular functions?

Also I was under impression that Rust at least has a similar goal?

▲tialaramex 12 hours ago | parent | next [-]

> Also I was under impression that Rust at least has a similar goal?

Rust's choice here is slightly different, Rust wants to give all of the types features, whereas C++ wanted to specifically give the user defined classes as much functionality as possible.

So in Rust 5 and "Five" and '5' and [5, 5, 5, 5, 5] all can have the features you get in your own custom type named Five whereas in C++ they do not. In C++ they're not allowed to have methods ("member functions") because they are "just" primitive types. In Rust the operators are actually implemented for all the types they can be used on, not just for your own user defined classes and so on.

In a few cases this is "fake", for your own type to have a + operator you'd have to write an implementation of addition and the Rust stdlib provides an "implementation" for the machine integers which says nothing of importance because of course in reality that code is never executed, the Rust compiler knew how to add two integers together already. However most of them are real albeit often trivial.

Because Rust doesn't privilege a specific user defined type, all the user defined types get the features which make sense, including not only struct but also enum and union. It still surprises me that C++ never gave enum class (its improvement on the C enum user defined type) methods, of course a Rust enum has methods.

▲pjmlp a day ago | parent | prev [-]

Initialisation syntax, and temporary values for implicit conversions, is what is lost.

▲aw1621107 a day ago | parent [-]

Both those feel a bit like circular arguments? They need constructors because that's how they are currently defined, but that doesn't say anything about whether they could also be defined without constructors.

The latter was what I was interested in, and I apologize for not making that clear. For instance, in Rust terms both those seem replaceable in principle via calls to appropriate trait functions like Default::default() or From::from().

▲pjmlp a day ago | parent | next [-]

Nope, because you also want C types, that now are C++ types by virtue of using a C++ compiler, to also share similar behaviours.

Which is why the only difference between a struct and a class, is the default access method.

Thus that C file could be made extensible in C++, with zero code changes on the call sites.

▲pwdisswordfishq a day ago | parent | next [-]

What does this have to do with anything?

▲ninkendo a day ago | parent | prev [-]

They could have just as easily said "C semantics are used when we know we're parsing C code" and declared that C++ code doesn't have implicit constructors. No, the decision to have constructors was made because it's what they wanted to do when the language was designed. You can't lean on "but C" as an excuse when those problems are so easily solved other ways.

▲0x457 a day ago | parent | prev [-]

Well, in Rust, you can't make your own Box without using #[lang = "owned_box"] and #[fundamental], plus it has special orphan rule handling.

The question is, at least for me, do you really miss out on anything by not having an ability to do so? I think you miss anything, but you gain a lot.

▲aw1621107 a day ago | parent [-]

> Well, in Rust, you can't make your own Box without using #[lang = "owned_box"] and #[fundamental], plus it has special orphan rule handling.

Sure, but are those "just" characteristics of Rust's current implementation or are those inherent to a constructor-less model in general? The latter is the more interesting question to me in this particular context, and I think it's similar to the question you express.

▲0x457 a day ago | parent [-]

Fair.

I think guaranteed in-place initialization is probably the strongest example of something that cannot be expressed through From or Default alone. There are proposals to solve this via traits. I haven't dug deep enough into them, but I'd assume those would be "special" traits that rely on compiler-provided semantics not otherwise expressible in ordinary library code.

Right now, both Box::new() and the vec![] macro resort to compiler intrinsics (write_via_move and write_box_via_move), particularly to avoid unnecessary intermediate storage and excessive stack usage.

▲aw1621107 19 hours ago | parent [-]

At least from what I can remember the work is in an early enough stage that multiple proposals being considered. IIRC dedicated syntax is in the cards as well.

▲ a day ago | parent | prev | next [-]
[deleted]
▲ninkendo a day ago | parent | prev [-]

I don't see the link between constructors and whether or not built-in types have special treatment. Care to enlighten the class?

▲quietbritishjim a day ago | parent | next [-]

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.

▲ninkendo a day ago | parent | next [-]

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.

▲steveklabnik a day ago | parent | next [-]

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 a day ago | parent | prev | next [-]

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.

▲ninkendo a day ago | parent [-]

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

Right, see the "I guess the argument might be" part above... I find this to be a very questionable design choice, leaving you to have to go and read a header somewhere to determine whether `Foo f;` is safe or not. But it's not really a choice, is it? C++ had to do it this way to be compatible with how C programs were written back in the 1970s.

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

Ah yes, the "but C can be configured to be not-insane" argument, one of my favorite pjmlp-isms, right up there with "but $LANG's compiler is written in C++" and "but you already get memory safety with a GC". Keep on doing you!

▲quietbritishjim a day ago | parent | prev [-]

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?

▲tialaramex a day ago | parent | next [-]

Rust has a Default trait, if your type Goose has a Default then

let foo: Goose = Default::default();

Those "primitive" types have a Default, the integers default to zero, as do the floating point types, bool defaults to false, I believe an empty string is the default string (in both the sense that's the default for String, and the default for str, the string slice reference roughly analogous to C++ string_view)

Some things don't have a sane default, just as those things wouldn't provide a zero argument constructor in C++. There isn't a default file descriptor, a default network socket, and so on and so those types do not implement Default

▲quietbritishjim a day ago | parent [-]

That makes sense, thanks!

▲ninkendo a day ago | parent | prev [-]

Yep, that's std::mem::zeroed(), which just writes zeroes into the allocated memory regardless of its type... also only available in unsafe code.

    #[derive(Debug)]
    struct Foo {
        _i: i32,
    }

    fn main() {
        let x: i32 = unsafe { std::mem::zeroed() };
        println!("x={x}");
        let f: Foo = unsafe { std::mem::zeroed() };
        println!("f={f:?}");
    }
prints:

    x=0
    f=Foo { _i: 0 }
It's unsafe because if Foo contained a String, it would be string with a null pointer inside it and you'd crash trying to read it. If you want "Default" values instead of zeroed (ie. you don't want to run unsafe code), that's what the Default trait is for, and this becomes:

    #[derive(Debug, Default)]
    struct Foo {
        _i: i32,
    }

    fn main() {
        let x: i32 = Default::default();
        println!("x={x}");
        let f: Foo = Default::default();
        println!("f={f:?}");
    }
and prints the same thing.
▲pwdisswordfishq a day ago | parent | prev [-]

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

▲steveklabnik a day ago | parent [-]

"uninitialized" is not a synonym for "random value", it's a totally different state.

https://www.ralfj.de/blog/2019/07/14/uninit.html

▲pwdisswordfishq 8 hours ago | parent [-]

Nowhere did I imply it is.

▲William_BB a day ago | parent | prev [-]

If my understanding is correct, C++ built-in types can be declared without initializing them:

  int x;   // Unitialized, garbage value
  int x{}; // Value-initialized (falls back to zero-initialization)
We want classes to have the same behaviour:

  Struct s;   // Default-initializes (presumably we want members uninitialized)
  Struct s{}; // Value-initializes (presumably we want members initialized)
▲ninkendo a day ago | parent [-]

As I replied in a sibling comment to yours, at least one language without constructors (Rust) has the exact same semantics for built-in types vs library types here. You must initialize in typical code, and the escape hatch is std::mem::uninitialized() which lets you work with uninitialized data, and this is true for any type, built-in or otherwise.

▲tialaramex a day ago | parent [-]

For many years now, This function is deprecated. Use MaybeUninit<T> instead.

core::mem::uninitialized is of course unsafe, but what people who designed it hadn't really appreciated was that in most cases it was impossible to use it correctly, it almost might as well have been a call to core::hint::unreachable_unchecked

If your type is a ZST then core::mem::uninitialized was safe to use, because not initializing zero bytes of RAM is the same as initializing all zero of them, this can't possibly matter so we're fine. Otherwise though, we create values which the LLVM backend is sure we cannot know and so it feels entitled to optimise as if any assumptions we make about those values are false, even if the results are contradictory. This causes immediate Undefined Behaviour all over the place.

The MaybeUninit<T> wrapper type is pretty easy to use and won't invoke Undefined Behaviour so long as you do everything in the instructions.

▲ninkendo a day ago | parent [-]

I literally had `MaybeUninit::uninit().assume_init()` first in the comment but rewrote it with `std::mem::uninitialized()` because I thought it would be more readable to a C++ crowd, but perhaps your right, I should have left it as-is.

▲tialaramex a day ago | parent [-]

MaybeUninit::uninit().assume_init() is, exactly like the deprecated† core::mem::uninitialized() immediately UB unless your type is zero size and thus there's no difference between initialized and uninitialized.

You can unsafely ask for an uninitialized value of any type, but you should not ever assert that you've initialized it unless you actually have. Essentially, you can write this in Rust, but you need to be specific about what you're doing and when you are or are not initializing the variable or else things will go badly for you.

It wouldn't be worse in C++, historically, but C++ people are more used to their world being set on fire by an angry compiler because they did something wrong. In Rust you'd be quite surprised by the compiler's wrath.

† Edited to add: Technically today you do not get this if you call core::mem::uninitialized, because it was so dangerous, instead if you call the deprecated function on a non-ZST - ironically you get a a value scribbled with 0x01 bytes. Doing this ensures in most cases LLVM won't set fire to your program immediately but at a price of doing all that extra work of writing 0x01 bytes. But we did tell you (for several years now) how to do better.

▲ninkendo a day ago | parent [-]

I completely agree, but the point was to show Rust code that does the same thing as the (equally unsafe) C++ code, and particularly that it doesn't treat built-ins any different than other types. But nobody should be writing code like this in either language.

To me the whole point of an "uninitialized variable" is to declare it in one place and then assign it in exactly one code path, which is exactly what rust supports without any unsafe code:

  let i: i32;
  if is_tuesday {
      i = 0;
  else {
      i = 1;
  }
  foo(i);
is already perfectly valid, safe rust code, because the compiler knows that all code paths result in assignment before use. And the answer to "what happens on that first line?" is "nothing", because it's just a declaration. In the equivalent C++ you'd be running an arbitrary constructor on the first line, and hoping the compiler optimizes it away. Or if the default constructor doesn't exist or is deleted, you simply can't code that way.
▲tialaramex a day ago | parent | next [-]

Your code snippet is fine, but MaybeUninit comes into its own when it's not obvious to the compiler that what you wrote is OK - MaybeUninit::assume_init is how you tell the compiler "I promise this is correctly initialized" and so long as you're correct, everything is fine. By Rice's Theorem no compiler could ever be sure all the time, and in fact Rust choose to be extremely pessimistic, obvious things like yours work, non-obvious things do not and if you write a ticket about a case you feel ought to be obvious but was not (please don't) the Rust folks will say that is as intended, here are some alternatives to achieve what you meant, up to and including MaybeUninit

▲TinkersW 11 hours ago | parent | prev [-]

In C++ you can do: int i = is_tuesday ? 0 : 1;

▲ninkendo 10 hours ago | parent [-]

Well, sure, in Rust you can do `let i = if is_tuesday { 0 } else { 1 };`, what's your point?

Imagine it's 10 variables instead of one, and the value you set them to is based on much more complex/nested logic. Sometimes for readability it's nice to declare and specify their types up front, then you go about initializing them all via some complex logic, then you use them later. The compiler should guarantee that they're all initialized before use. There's no real way to do this in C++ every time: For primitives it works, but for other types, it needs a no-argument constructor available or the code won't compile, and even if a no-argument constructor is available, the compiler will needlessly run that constructor even though it doesn't need to (and maybe it'll optimize that away but who knows.)

You can obviously make this work in C++ by (subjectively) decreasing readability, but wouldn't it be nicer if declaration was an explicit thing separate from initialization, and the compiler would simply enforce that it's safe?