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

Reply via email to