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?
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.
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
No, delete[]
only deallocates an array created by new[]
© 2022 - 2024 — McMap. All rights reserved.
delete[] a
. – Dimple