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?
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.
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.
delete is used for one single pointer and delete[] is used for deleting an array through 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).
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With