C++ deleting a pointer to a pointer

前端 未结 7 582
猫巷女王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:27

    Yes you have to loop over the pointers, deleting individually.

    Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit.

    For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code.

提交回复
热议问题