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

前端 未结 9 1498
-上瘾入骨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条回答
  •  既然无缘
    2020-11-22 03:36

    ONE OF THE approaches for compilers is to allocate a little more memory and to store a count of elements in a head element.

    Example how it could be done:

    Here

    int* i = new int[4];
    

    compiler will allocate sizeof(int)*5 bytes.

    int *temp = malloc(sizeof(int)*5)
    

    Will store "4" in the first sizeof(int) bytes

    *temp = 4;
    

    and set i

    i = temp + 1;
    

    So i will points to an array of 4 elements, not 5.

    And deletion

    delete[] i;
    

    will be processed in the following way:

    int *temp = i - 1;
    int numbers_of_element = *temp; // = 4
    ... call destructor for numbers_of_element elements
    ... that are stored in temp + 1, temp + 2, ... temp + 4 if needed
    free (temp)
    

提交回复
热议问题