Deleting multiple pointers with single delete operator [closed]
Asked Answered
C

2

11

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?

Cosmic answered 15/9, 2013 at 8:27 Comment(2)
Because there is no syntax for it. Because Bjarne didn't put it in. It's not a real question, unless you can find someone on the ANSI or ISO committee who was present when and if it was ever considered.Jeannettajeannette
Antoine de Saint-Exupery once wrote In anything at all, perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away. Likewise, a programming language is not made better by including anything and everything; it is just made more complex.Reorientation
R
14

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

Rameriz answered 15/9, 2013 at 8:30 Comment(0)
H
1

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.

Hangeron answered 15/9, 2013 at 8:30 Comment(4)
@john: I think Nick is referring to a container or array, rather than a struct.Rameriz
You can either use a loop with an index increasing to get the index each time, or, if it is about a container, to use an iterator object.Hangeron
@MatsPetersson You are right (updated the answer), but this is on his choice on what to use, structures or container classes.Hangeron
In C++11 you can write your own variadic "deletes" function. Even simpler is: for (auto &p : {pointer1,pointer2}) { delete p; }.Chrestomathy

© 2022 - 2024 — McMap. All rights reserved.