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

Gary Willoughby via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 20 03:48:54 PDT 2017


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?


import std.stdio;
import core.stdc.stdlib : malloc, calloc, free;

struct Foo
{
	public int* _foo;

	public this(int n)
	{
		this._foo  = cast(int*) malloc(int.sizeof);
		writefln("ctor: %x", this._foo);
	}

	public this(this)
	{
		writefln("post blit: %x", this._foo);
	}

	public ~this()
	{
		// Why is this._foo null here???
		writefln("dtor: %x", this._foo);
	}
}

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;
		}
	}
}

void main(string[] args)
{
	auto bar = Bar(1);
}



More information about the Digitalmars-d-learn mailing list