On Wednesday, 22 February 2017 at 13:00:19 UTC, Kagamin wrote:
On Sunday, 19 February 2017 at 11:41:44 UTC, Eugene Wissner wrote:
realloc() can move memory and if an object of type A has references to other objects in the array, the objects will be corrupted. "A" should be a POD-type. Otherwise you have to allocate new memory, initialize it, copy the objects by one and deallocate the old memory. Now there is IAllocator.expand().


What's the difference between realloc+postblit and copy one by one? Postblit is called only after copy, it's not a constructor.

The difference is that realloc will deallocate the old memory before postblit.
For the sake of example:

struct Sample
{
        Sample* sample;

        this(this)
        {
                sample.sample = &this;
        }
}

void main()
{
        auto s = new Sample[2];

        s[0].sample = &s[1];
        s[1].sample = &s[0];
}

Now suppose s[0] has the address 7fc8d2717000, s[1]: 7fc8d2717008.
Realloc cannot reallocate in place and after the call to realloc s[0] has the address 7f27771e0000 and s[1]: 7f27771e0000. It is too late to call the postblit here, Sample.sample refers to invalid memory.

Reply via email to