Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ deleting a pointer to a pointer

Tags:

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 pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question.

(And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)

like image 785
Jason Baker Avatar asked Sep 07 '08 03:09

Jason Baker


People also ask

How do you remove a pointer from a pointer?

You usually delete the object that a pointer is pointing to, rather than the pointer itself. You can do this using the “delete” keyword if the object was allocated using the “new” keyword, otherwise if the memory was allocated using malloc(), you would need to call the free() function.

What happens when you delete a pointer to a pointer?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).

Can we delete the pointer in C?

You cannot 'delete' a null pointer. Strictly speaking, the C programming language has no delete (it is a C++ keyword), it just provides the free[^] function. In any case, free on a null pointer does nothing.

Does delete delete a pointer?

delete keyword in C++ New operator is used for dynamic memory allocation which puts variables on heap memory. Which means Delete operator deallocates memory from heap. Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed.


1 Answers

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.

like image 185
Jason Cohen Avatar answered Sep 18 '22 03:09

Jason Cohen