C++ deleting a pointer to a pointer

前端 未结 7 569
猫巷女王i
猫巷女王i 2020-12-24 14:41

So I have a pointer to an array of pointers. If I delete it like this:

delete [] PointerToPointers;

Will that delete all the pointed to po

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 15:22

    I don't know why this was answered so confusingly long.

    If you delete the array of pointers, you will free the memory used for an array of usually ints.
    a pointer to an object is an integer containing the adress.

    You deleted a bunch of adresses, but no objects.

    delete does not care about the content of a memory space, it calls a destructor(s) and marks the mem as free.

    It does not care that it just deleted a bunch of adresses of objects, it merely sees ints.

    That's why you have to cycle through the array first! and call delete on every element, then you can delete the storage of the array itself.

    Well, now my answer got somewhat long... .... strange... ;)

    Edit: Jason's answer is not wrong, it just fails to hit the spot. Neither the compiler nor anything else in c(++) cares about you deleting stuff that is elsewhere pointed to. You can just do it. Other program parts trying to use the deleted objects will segfault on you. But no one will hinder you. Neither will it be a problem to destroy an array of pointers to objects, when the objects are referenced elsewhere.

提交回复
热议问题