Arrays of structs

SimonN via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 27 03:24:07 PDT 2015


Hi,

On Thursday, 27 August 2015 at 10:05:31 UTC, John Burton wrote:
> understanding is that structs have deterministic destructors - 
> they are called when the struct goes out of scope

Yes, when they are declared right at the scope, and not contained 
in something that might live past the current scope.

> However if I add them to a dynamic array...
> Then the destructor appears to be called at some random time 
> later. So it looks like it's the garbage collection that is 
> doing this.

Yeah.

> That seems to go against the specification of how struct 
> works... I'm not creating the item with "new" and as far as I 
> can tell the array is storing instances of objects, not 
> pointers to objects?

The array is storing the full structs, yes. The array is GC-ably 
allocated and will therefore not go out of scope at end of scope. 
Because the array doesn't vanish here, the structs inside will 
not go out of scope either; they treat the array as their scope.

(I'm sure others could explain this more formally.)

There is no reference left to the array, so the GC may at a 
random later time deallocate the array, and thereby call ~this() 
on each struct.

> Is my understanding correct?

Explicit "new" is not the only way to put objects on the GC'ed 
heap. Putting them in a GC-ed array like this is another way. Or 
having them as a component in a class, then instantiating that 
class.

> Is it documented anywhere how memory allocation works for this?

I'll leave this for others, too.

> Is a dynamic array in fact storing an array of GC'd pointers to 
> the structs?

No, it's the full struct.

-- Simon


More information about the Digitalmars-d-learn mailing list