@disable("reason")

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jan 9 10:19:45 UTC 2020


On Wednesday, January 8, 2020 2:58:59 PM MST Marcel via Digitalmars-d-learn 
wrote:
> On Wednesday, 8 January 2020 at 07:03:26 UTC, Jonathan M Davis
>
> wrote:
> > On Tuesday, January 7, 2020 5:23:48 PM MST Marcel via
> >
> > Digitalmars-d-learn wrote:
> >> [...]
> >
> > In terms of an error message? Not really. You can put a
> > pragma(msg, ""); in there, but that would always print, not
> > just when someone tried to use it. I'd suggest that you just
> > put the information in the documentation. If they write code
> > that doesn't work because of you using
> >
> > [...]
>
> Oops, it appears I didn't actually understand this part of the
> language. I'm coming from C++ and I assumed both languages did
> this the same way, but thankfully I found a workaround that
> doesn't require doing what I wrote in the initial post and is
> better in general.

D took the approach of having all variables being default initalized with a
value that's known at compile-time so that you don't risk dealing with
garbage values as can happen in C/C++. For structs, the result is that
default constructors aren't a thing, because the default vaule has to be a
fixed value known at compile time, and that doesn't work with default
constructors, which can run arbitrary code at runtime. And with non-default
constructors, a struct is actually initialized with its default value before
its constructor is even run. So, you don't risk reading garbage values in
the object's member variables before properly initializing them.

There are times when the lack of default constructors can be annoying, but
it avoids a class of problems that C++ has, and overall, it works quite
well.

The ability to @disable this(); was added later in order to facilitate rarer
cases where using the default value for a type would be problematic (e.g.
when a type absolutely needed to have some code run at runtime when
constructing it for it to work properly). However, because the language was
designed around the idea that all objects would be default-initialized,
disabling default initialization tends to make some typical stuff not work
with that type (like out parameters or arrays, since they both require the
init value).

Ultimately, D's approach is a tradeoff. Some of the problems that you can
have in C++ are eliminated, but it introduces some complications that don't
exist in C++.

> I also agree with Adam, it can make for a nice little feature in
> D.

I doubt that there would be much resistance to it, but since you almost
certainly need to read the documentation to understand how to use the type
properly if it can't be default-initialized, I don't know that it would
actually add much benefit in practice. Either way, it's not something that's
come up often enough for anyone to push for such a language change.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list