Question

Does delete[] a, where a is dynamic-allocated array of pointers, execute delete for each pointer in array?

I suppose, it executes destructor for arrays with user-defined classes, but what's happening with pointers?

Was it helpful?

Solution

No, delete [] is used to delete an array. If you need to delete array elements, you need to call delete on each one of them.

OTHER TIPS

No. Raw pointers contain no information about how (or whether) their target should be deallocated, so destroying one will never delete the target.

This is why you should never use them to manage dynamic resources - you have to do all the work yourself, which can be very error-prone. Instead, you should use RAII, replacing the pointers with containers, smart pointers, and other classes that manage resources and automatically release them on destruction. Replace your dynamic array with std::vector (or std::vector<std::unique_ptr>, if you really need to allocate each object individually) and everything will be deallocated automatically.

No, if a is a dynamically-allocated array of raw pointers, delete[] a; just deletes the memory occupied by the raw pointers array, but it does not call the destructors for the objects pointed to.

So, if these raw pointers are owning pointers, you have leaktrocity :)

Use an STL container class with smart pointers, e.g. std::vector<std::unique_ptr<X>>, for a more modern and simpler approach: in this way, you get both exception-safety and automatic destruction of both the array of pointers, and the objects pointed to.

delete[] will call the destructor of each element of the array. As a pointer is a basic type it doesn't really have a destructor, so it does nothing.

That's exactly why smart pointers are used: delete[] will call the destructor of each element, and the destructor of the smart pointer will call delete on the managed pointer.

So: learn about smart pointers and stop managing memory by hand. It's easier, less error prone, and less low level.

The delete[] will only remove the elements in the array.It will not remove the memory pointed by array elements. If you want to delete the memory pointed by the array elements

  1. Delete each memory explicitly by calling delete on each array elements
  2. Then delete the array by delete[] operator

No, delete[] only deallocates an array created by new[]

See the reference for more informations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top