Default value for member class
Steven Schveighoffer
schveiguy at gmail.com
Mon Feb 10 18:36:55 UTC 2020
On 2/10/20 1:18 PM, JN wrote:
> class IntValue
> {
> int x = 5;
> }
>
> class Foo
> {
> IntValue val = new IntValue();
> }
>
> void main()
> {
> Foo f1 = new Foo();
> Foo f2 = new Foo();
>
> assert(f1.val == f2.val);
> }
>
>
> Is this expected?
Define "expected" ;)
It's been this way for a while actually. It's the way it's currently
implemented, but I wouldn't say that anyone really expects this. The end
result is you just shouldn't create default values for object members.
> Or should each Foo have their own IntValue object?
That would be ideal.
> They're equal right now, changing one changes the other. When exactly is
> the "new IntValue" happening? On program init, or when calling new Foo()
> for the first time?
The new IntValue is happening at compile-time and stuck in the static
data segment. Then every new instance of Foo gets a pointer to that one
instance.
-Steve
More information about the Digitalmars-d-learn
mailing list