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

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

delete[] monsters;

Is incorrect because monsters isnt 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 doesnt 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.

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

To simplify the answare lets look on the following code:

#include stdafx.h
#include <iostream>
using namespace std;

class A
    int m_id;
    static int count;
    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()
    return 0;

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

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

try to use delete[] arr; the output is:
Destructor A 10
Destructor A 9
Destructor A 8
Destructor A 7
Destructor A 6
Destructor A 5
Destructor A 4
Destructor A 3
Destructor A 2
Destructor 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 well use delete arr instead of delete[] arr. it will not delete the whole pointers in the array => memory leak of pointer objects!

Leave a Reply

Your email address will not be published.