Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting array of pointers

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?

like image 698
Krzysztof Stanisławek Avatar asked Feb 12 '14 15:02

Krzysztof Stanisławek


2 Answers

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.

like image 69
juanchopanza Avatar answered Sep 27 '22 16:09

juanchopanza


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.

like image 39
Mike Seymour Avatar answered Sep 27 '22 17:09

Mike Seymour