Disallowing S() when struct S has a constructor
Quirin Schroll
qs.il.paperinik at gmail.com
Fri Sep 6 09:45:39 UTC 2024
On Thursday, 5 September 2024 at 18:17:33 UTC, Paul Backus wrote:
> On Thursday, 5 September 2024 at 17:46:18 UTC, Quirin Schroll
> wrote:
>> - Deprecate `init`. Replace it with `default(T)` (read:
>> “default of `T`”) which gives you an uninitialized object of
>> type `T` that might or might not be usable. It can’t be hooked
>> (unlike `init`) because `default` is a keyword. A constructor
>> transforms a the `default(T)` object into an object that
>> satisfies the invariants of `T` if any. In general, using
>> `default(T)` is a bad idea unless you do it knowing full well
>> what you’re getting.
>
> Wouldn't it be easier to just forbid user-defined `.init`
> properties? It's a breaking change either way.
>
>> - A default constructor is only implicitly present if all data
>> members have a default constructor and no constructor is
>> explicitly defined.
>
> Would this also apply if some members have default constructors
> and the others are things like integers or POD structs?
In principle, yes. If every data member’s type `T` supports
`T()`, I consider it having a default constructor. The reason why
`T()` works is irrelevant, maybe excluding `static opCall`.
>> - A default constructor can be explicitly set to be the
>> generated one using `default`: `default this();`
>
> We already have compiler-generated default implementations for
> copy constructors and `opAssign`, and neither of them support
> this kind of explicit declaration. Why is it necessary to have
> this for default constructors, if it wasn't necessary for copy
> constructors and `opAssign`?
Because defining any constructor makes the compiler not generate
a default constructor. It’s a way to say: Give me the default
constructor without spelling it out. Maybe I’m leaning too much
into the C++ direction, and `this() {}` would absolutely work.
But generally, `default this();` would make the default
constructor have attributes and `this() {}` would not. If that’s
the only difference, it maybe isn’t worth it.
More information about the Digitalmars-d
mailing list