A question about postblit constructor

Ferhat Kurtulmuş aferust at gmail.com
Tue Nov 5 12:19:06 UTC 2019


On Tuesday, 5 November 2019 at 12:09:15 UTC, Ferhat Kurtulmuş 
wrote:
> On Tuesday, 5 November 2019 at 12:06:44 UTC, Ferhat Kurtulmuş 
> wrote:
>> On Tuesday, 5 November 2019 at 11:20:47 UTC, Mike Parker wrote:
>>> On Tuesday, 5 November 2019 at 10:32:03 UTC, Ferhat Kurtulmuş 
>>> wrote:
>>>>>[...]
>>>
>>> I meant the example as an answer to your statement, "I wonder 
>>> how new memory is allocated without an explicit malloc here". 
>>> The postblit was intended as a chance to "fixup" everything 
>>> when you needed a deep copy. The new struct is initialized as 
>>> a shallow copy, so when you enter into the postblit, the 
>>> pointer is already pointing at the original location. Without 
>>> assigning it a new malloc'ed address, your memcpy was 
>>> essentially overwriting the original location with its own 
>>> data.
>>
>> What I need was a deep copy, and I thought I could have done 
>> it using postblit constructor. Thanks for clarification.
>
> I think copy constructor is less confusing though.

Oh I see I have to do this to make a deep copy using postblit 
constructor:

     this(this){
         int* _vals = cast(int*)malloc(length * S.sizeof);
         foreach(i; 0..length)
             _vals[i] = vals[i];
         vals = _vals;
         writeln("copied");
     }


More information about the Digitalmars-d-learn mailing list