How does delete[] “know” the size of the operand array?

前端 未结 9 1607
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:50
Foo* set = new Foo[100];
// ...
delete [] set;

You don\'t pass the array\'s boundaries to delete[]. But where is that information stor

9条回答
  •  Happy的楠姐
    2020-11-22 03:24

    This is a more interesting problem than you might think at first. This reply is about one possible implementation.

    Firstly, while at some level your system has to know how to 'free' the memory block, the underlying malloc/free (which new/delete/new[]/delete[] generally call) don't always remember exactly how much memory you ask for, it can get rounded up (for example, once you are above 4K it is often rounded up to the next 4K-sized block).

    Therefore, even if could get the size of the memory block, that doesn't tell us how many values are in the new[]ed memory, as it can be smaller. Therefore, we do have to store an extra integer telling us how many values there are.

    EXCEPT, if the type being constructed doesn't have a destructor, then delete[] doesn't have to do anything except free the memory block, and therefore doesn't have to store anything!

提交回复
热议问题