Deleting multiple pointers with single delete operator

zer0Id0l picture zer0Id0l · Sep 15, 2013 · Viewed 9.4k times · Source

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?

Answer

Mats Petersson picture Mats Petersson · Sep 15, 2013

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")