Why would an initialised struct pointer field be null in the struct's destructor?

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 20 04:15:57 PDT 2017


On Saturday, 20 May 2017 at 10:48:54 UTC, Gary Willoughby wrote:
> In the following code, the `_foo` pointer (of the Foo struct) 
> is null in the first call to the destructor. Why is this? I 
> think it's got something to do with the foreach loop but I'm 
> not sure. Any ideas?
>
> struct Bar
> {
> 	private Foo[] _data;
>
> 	public this(int n)
> 	{
> 		this._data = (cast(Foo*) calloc(n, Foo.sizeof))[0 .. n];
>
> 		foreach(ref element; this._data)
> 		{
> 			auto tmp = Foo(1);
> 			element = tmp;
> 		}
> 	}
> }

Because `element = tmp` destroys `element`, which you allocated 
filled with zeroes.
The destructor will run for each `element`.


More information about the Digitalmars-d-learn mailing list