开发者

new[n] and delete every location with delete instead the whole chunk with delete[]

开发者 https://www.devze.com 2022-12-24 12:08 出处:网络
Is this valid C++ (e.g. not invoking UB) and does it achieve what I want without leaking memory? valgrinds complains about mismatching free and delete but says \"no leaksare possible\" in the end.

Is this valid C++ (e.g. not invoking UB) and does it achieve what I want without leaking memory? valgrinds complains about mismatching free and delete but says "no leaks are possible" in the end.

int main() {
  int* a = new int[5];
  for(int i = 0; i < 5; ++i)
    a[i] = i;

  for(int i = 0; i < 5; ++i)
    delete &a[i];
}

The reason I'm asking: I have a class that uses boo开发者_JAVA技巧st::intrusive::list and I new every object that is added to that list. Sometimes I know how many objects I want to add to the list and was thinking about using new[] to allocate a chunk and still be able to delete every object on its own with the Disposer-style of boost::intrusive.


No way. You cannot call delete on what was not allocated by new or you get heap corruption.

You see, that array created by new[] didn't allocate n individual objects, but one array. The second object of the array is in the middle of the allocation block.


You can add a bit so each object remembers whether it was the first in the contiguous array. This is tricky:

  • totally incompatible with delete object syntax
  • incompatible with inheritance
  • disposer instead calls destructor explicitly, eg object.~ListItem()
  • must still use array operator new[]
  • be sure to dispose objects in reverse order, unlike your included example
  • destructor implements reflective ownership of the array by its first element:

.

ListItem::~ListItem() {
    if ( m_own_my_subarray ) {
        operator delete[]( this ); // does not invoke any destructor!
                 // "this" must be exactly the result of new[]!
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消