On Sat, Nov 14, 2020 at 11:20:55PM +0000, Martin via Digitalmars-d-learn wrote:
> Hi, i do no know if this is intended - but imo this is weird:
> https://run.dlang.io/is/eBje3A
> 
> I expected that `c.a.str == ""` (just like `c.str` is). But instead
> `c.a.str` keeps the value of `b.a.str`.
> 
> Is this intentional? IMO this feels not consistent and its weird when
> a reference leaks into another instance without having declared it
> static member.
[...]

This is a known "feature".  Using a `new` expression as a field
initializer will initialize it once at program startup, and the
reference is copied thereafter into all instances of the class.

If you want separate instances per class instantiation, move the `new`
into the constructor instead.

Yes, it does feel weird, and IMNSHO it's a misfeature. But it is what it
is; if you don't like the semantics, don't use it; always allocate the
field in the class ctor instead.


T

-- 
The fact that anyone still uses AOL shows that even the presence of options 
doesn't stop some people from picking the pessimal one. - Mike Ellis

Reply via email to