Hello,

I have a simple question. Look at the following code:

class ClsA {

int * var1;

ClsA();
~ClsA();

}

ClsA::ClsA(){
   var1 = new int [10];
}

ClsA::~ClsA{
   delete [] var1;
   cout<<"Apel destructor";
}

void funct(){
	ClsA ** p = new ClsA * [10];
	.....

	delete [] p; 
}

When i give : " delete [] p " the destructor of ClsA is not automatically call! So, i must explicitly call the destructor? if i let only the " delete [] p " is enough? I will have memory lacks?

thanks!

Recommended Answers

All 2 Replies

p does not point to any ClsA objects, p points to a pointer to ClsA objects.

A pointer is a built in type and has no constructor or destructor. So no destructor call is required for that delete statement.

Presumably in the code lines 21-22 you have something that does p[0] = new ClsA[10]; and the destructor will be called when you delete this memory delete[] p[0];

Hi etisermars :-)

The line

delete [] p;

will only delete the array of pointers, not the objects the pointers point to.

You will have to handle the destruction of the ClsA-objects yourself. If you don't you will have a memory leak.

Have a look at my simplified example, and comments:

void funct(){
    ClsA ** p = new ClsA * [10]; //Create array of 10 pointers to ClsA-objects

    //Create 10 new ClsA-objects and make the pointers point to them
    for(int i = 0; i < 10; i++)
        p[i] = new ClsA();

    //If you don't delete the objects you will have a memory leak!
    for(int j = 0; j < 10; j++)
        delete p[j];

    delete [] p; //Delete array of pointers, but not the actual objects
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.