dimanche 30 juin 2019

Why don't I need to delete a temporay dynamic array sometimes?

We are always told to delete what is initialised with the new keyword, like dynamic arrays.

But I found that when people doing something like what is shown below, they do not delete the temporary dynamic array manually. But I think we should delete int* temp, otherwise it will become a dangling pointer. It came from the heap, so it never goes out of scope until the program ends.

void A::realloc(std::size_t size)
{
    // don't care about the contents of this->arr
    int* temp = new int[size];
    std::copy(this->arr, arr + this->size, temp);
    delete[] this->arr;
    this->arr = temp;
}

Aucun commentaire:

Enregistrer un commentaire