Class member initialization with new points to a single instance?

mw mingwu at gmail.com
Wed Jun 9 18:43:51 UTC 2021


On Wednesday, 9 June 2021 at 18:12:01 UTC, Gregor Mückl wrote:
> On Wednesday, 9 June 2021 at 18:04:54 UTC, evilrat wrote:
>> On Wednesday, 9 June 2021 at 17:56:24 UTC, Gregor Mückl wrote:
>>> Consider the following code:
>>>
>>> ```d
>>> class Foo {  }
>>>
>>> class Bar { Foo foo = new Foo(); }
>>>
>>> void main()
>>> {
>>> 	Bar b1 = new Bar();
>>> 	Bar b2 = new Bar();
>>>
>>> 	assert(b1.foo != b2.foo);
>>> }
>>> ```
>>>
>>> The assert fails. This is completely surprising to me. Is 
>>> this actually expected?
>>
>> By design.
>> What you see is CTFE instance shared through class member 
>> initializer.
>>
>> Use Bar ctor instead if you want them to be unique.
>>
>> Yep, confusing for the first time.
>
> My two cents:
>
> I think this should be changed because all other common 
> languages that support equivalent syntax have settled on 
> runtime initialization for this. But it's probably too deeply 
> embedded into the language now. :(

Can we add (enforcement) `static` in this case, to make it clear. 
It's so confusing.




More information about the Digitalmars-d-learn mailing list