Please fix `.init` property

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Jan 8 18:03:00 UTC 2024


On Monday, January 8, 2024 3:57:52 AM MST FeepingCreature via Digitalmars-d 
wrote:
> > However, ultimately, that's not really what the OP seems to be
> > complaining about. Rather, he seems to be complaining about the
> > fact that if you mutate a member variable with mutable
> > indirections which were not null in the init value, then the
> > changes to those mutable indirections are visible via the init
> > value, and I don't think that that's something that's ever
> > going to change, because it would require that default
> > initialization do a deep copy rather than a shallow copy.
> > Obviously, it can be surprising if it's not something that
> > you've run into or thought through before, but D doesn't have a
> > generic way to do deep copies, and you wouldn't necessarily
> > want a deep copy in all cases anyway, so even if we could make
> > it do a deep copy, that wouldn't necessarily be a good change
> > for the language as a whole, though it would certainly fix the
> > issue that the OP ran into.
> >
> > Arguably, what the OP needs is a default constructor rather
> > than an init value, but that's not the way that D is designed,
> > and it would be problematic with some of its features to use
> > default construction instead (though this is far from the only
> > case where not having default construction for structs can be
> > annoying).
>
> Force default values to be typed immutable?

That would require that there be a general way to copy an immutable value to
a mutable one, because the object must be mutable after it's been
default-initialized.

Also, if any sort of deep-copying occurs, then you end up in the bizarre
situation where code like

S s;
assert(s is S.init);

fails, which is also problematic.

Bastiaan's suggestion to make such cases illegal is probably the only sane
way to prevent these kind of issues, though I think that it would have to be
an error to have mutable indirections with an allocation rather than illegal
to point to any allocations; otherwise, stuff like SysTime's member which is
Rebindable(immutable TimeZone) becomes illegal.

- Jonathan M Davis





More information about the Digitalmars-d mailing list