A question about postblit constructor
Ferhat Kurtulmuş
aferust at gmail.com
Tue Nov 5 10:31:05 UTC 2019
On Tuesday, 5 November 2019 at 10:13:59 UTC, Mike Parker wrote:
> On Tuesday, 5 November 2019 at 08:47:05 UTC, Ferhat Kurtulmuş
> wrote:
>
>> 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.
>>
>
>> 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]);
>
> writeln(s2.vals);
> writeln(s1.vals);
>
>> }
>
> https://run.dlang.io/is/D0nfeT
Yep, it is obvious that my code is wrong. s1 and s2 point to the
same memory address. I could obtain my desired behavior with copy
constructor. The documentation also say "WARNING: The postblit is
considered legacy and is not recommended for new code. Code
should use copy constructors defined in the previous section".
struct S {
int* vals;
size_t length;
this(ref return scope S another) {
vals = cast(int*)malloc(another.length * S.sizeof);
memcpy(vals, another.vals, another.length * S.sizeof);
writeln("copied");
}
this(int* vls, size_t len){
vals = vls;
length = len;
}
~this(){
free(vals);
writeln("freedooom!");
}
}
More information about the Digitalmars-d-learn
mailing list