Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting multiple pointers with single delete operator [closed]

For deleting and an array of element we use delete[]. Is it possible to delete the pointers the way I am doing below?

ClassA* object = new ClassA();
ClassA* pointer1 = object;

ClassA* object2 = new ClassA();
ClassA* pointer2 = object2;

delete pointer1,pointer2;

Why its not possible to use delete this way?

[Edit]

Can I put it like, what are the drawbacks due to which the above delete has not been implemented?

like image 257
zer0Id0l Avatar asked Sep 15 '13 08:09

zer0Id0l


People also ask

What happens if you delete a pointer twice?

If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.

Does delete remove the pointer?

This removes the memory to which ps pointer points; it doesn't remove the pointer ps itself. You can reuse ps, for example, to point to another new allocation.

How delete [] is different from delete in C++?

delete is used for one single pointer and delete[] is used for deleting an array through a pointer.

What happens when you delete a pointer to a pointer?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).


2 Answers

It is not working this way. delete is a command for a single pointer. You can put the pointers in a structure (e.g. array) or a container (e.g. using a vector container class) and delete for each one of them by iterating the structure/container.

like image 66
Nick Louloudakis Avatar answered Oct 04 '22 01:10

Nick Louloudakis


It's not possible, because there is no provision for it in the C++ language definition. I'm not sure there is any "good" answer to why the language doesn't support a list of items for delete, except for the fact that it's simpler to not do that.

You need to write one delete for each variable. Of course, if you have many pointerX, then you probably should be using an array instead, and use a loop to delete the objects.

Edit: Of course, if you are calling delete in many places in your code, you are probably doing something wrong - or at least, you are not following the RAII principles very well. It's of course necessary to learn/understand dynamic allocation to have full understanding of the language, but you should really avoid calling both new and delete in your own code - let someone else sort that out (or write classes that do "the right thing")

like image 44
Mats Petersson Avatar answered Oct 04 '22 00:10

Mats Petersson