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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With