I am trying to learn behavior of postblit constructor. Below code works as expected when I comment out malloc part of postblit constructor. It writes 4 if malloc part of postblit constructor is commented out. Otherwise it writes default init value of int which is 0. I wonder how new memory is allocated without an explicit malloc here. Sorry for this noob question in advance, I could not find any doc mentioning a similar case.

import std.stdio;
import core.stdc.stdlib;
import core.stdc.string;

struct S {
    int* vals;
    size_t length;

    this(this){
        //vals = cast(int*)malloc(length * S.sizeof);
        memcpy(vals, vals, length * S.sizeof);
        writeln("copied");
    }
}

void main()
{
    size_t len = 2;

    int* vals = cast(int*)malloc(len * S.sizeof);
    vals[0] = 4;
    vals[1] = 5;

    S s1 = S(vals, len);

    S s2 = s1;

    writeln(s2.vals[0]);

}

Reply via email to