C++ Array of pointers: delete or delete []? C++ Array of pointers: delete or delete []? arrays arrays

C++ Array of pointers: delete or delete []?


delete[] monsters;

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)


For new you should use delete. For new[] use delete[]. Your second variant is correct.


To simplify the answare let's look on the following code:

#include "stdafx.h"#include <iostream>using namespace std;class A{private:    int m_id;    static int count;public:    A() {count++; m_id = count;}    A(int id) { m_id = id; }    ~A() {cout<< "Destructor A "   <<m_id<<endl; }};int A::count = 0;void f1(){       A* arr = new A[10];    //delete operate only one constructor, and crash!    delete arr;    //delete[] arr;}int main(){    f1();    system("PAUSE");    return 0;}

The output is:Destructor A 1 and then it's crashing (Expression: _BLOCK_TYPE_IS_VALID(phead- nBlockUse)).

We need to use: delete[] arr; becuse it's delete the whole array and not just one cell!

try to use delete[] arr; the output is:Destructor A 10Destructor A 9Destructor A 8Destructor A 7Destructor A 6Destructor A 5Destructor A 4Destructor A 3Destructor A 2Destructor A 1

The same principle is for an array of pointers:

void f2(){    A** arr = new A*[10];    for(int i = 0; i < 10; i++)    {        arr[i] = new A(i);    }    for(int i = 0; i < 10; i++)    {        delete arr[i];//delete the A object allocations.    }    delete[] arr;//delete the array of pointers}

if we'll use delete arr instead of delete[] arr. it will not delete the whole pointers in the array => memory leak of pointer objects!