I got confused about delete and delete[] especially about delete[]. Let's take an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
struct SomeItem
{
SomeItem(){ ... }
~SomeItem(){ ... } // should be called when delete
}
int main()
{
SomeItem **arr= new SomeItem*[10];
...
//Does not delete all elements if I comment out following for loop
for (int i....)
delete arr[i];
delete[] arr;
}
What I have read is that delete[] calls delete for each element, If that is true then it should work with just delete[] arr;
What I have read is that delete[] calls delete for each element,
It does not. It calls the destructor for each element.
However the destructor for pointers does nothing, so you must still delete individual pointers that have been allocated with new.
Is that because I am using arrary to pointers??
Basically yes.
The fundamental rule is that every new must have a matching delete.
The only real way to shortcut this would be to use smart pointers (see boost::ref_ptr and similar classes) or some other smart container (see boost::ptr_vector, and similar classes).
delete is not recursive. In the section you omitted ("...") you are allocating SomeItems via new. Every new must have a corresponding delete. The array delete will not delete those objects for you. They have to be deleted with the for loop in lines 14 & 15 just as you are doing.