Disallowing S() when struct S has a constructor
Quirin Schroll
qs.il.paperinik at gmail.com
Fri Sep 13 10:39:38 UTC 2024
On Sunday, 8 September 2024 at 00:00:49 UTC, Matheus Catarino
wrote:
> On Thursday, 5 September 2024 at 17:46:18 UTC, Quirin Schroll
> wrote:
>> C++ has had default constructors forever. It’s one of the few
>> decisions where I’m convinced that C++ got it right and D
>> isn’t. “Variable declarations must be cheap” is a dogma that
>> I’d expect in a language like C or Zig, not in a language like
>> D, where frequently, safety wins over performance. The fact
>> that I can declare a variable in D and it might not be safe to
>> use is a problem.
>>
>
> Apparently Zig is also about to adopt
> `.init`/`.default`/`.empty` during variable declaration. Even
> if there is no ctor/dtor (RAII).
>
> https://ziggit.dev/t/prefered-method-to-initialize-generalpurposeallocator/5875/13
As I read the thread, it’s specific to `GeneralPurposeAllocator`
and other structs for which compile-time default initialization
can’t be done. Zig’s `init` is a fully formed object that is a
run-time-initialized value specifically crafted for each type
that has it, very much unlike D’s `init`s.
Part of Zig’s dogma is that everything that happens has to be
explicit. Technically, there are no destructors in Zig, just
functions you’re supposed to call after an object isn’t needed
anymore, which you normally do using `defer`. The difference is,
every use of an object requires a `defer deinit();`, i.e. there
is no implicit destructor call. In D, we’re comfortable with
destructors and other implicit stuff, so a declaration implicitly
calling a default constructor is very much in line with what D
does elsewhere. It’s not even close to being that implicit as a
destructor call, actually.
“Make interfaces easy to use correctly and hard to use
incorrectly.” ―Scott Meyers
https://www.aristeia.com/Papers/IEEE_Software_JulAug_2004_revised.htm
A struct type for which `S s; s.f();` doesn’t really work, but `S
s = S(); s.f();` is bad design.
More information about the Digitalmars-d
mailing list