so, here is my example to explain this question
void * p1;
int * p2, * p3;
p2 = new int;
p1 = p2;
p3 = (int *) p1;
to free the memory, are the following 3 lines equivalent to each other?
delete p2;
delete p3;
delete (int *) p1;
the reason i am using such is that i want to pass a pointer between functions without knowing its type, for instance i define a void pointer and changes its value by calling other functions as follow:
void * p1;
func1(p1); //in this function, p2 = new int and p1 is assigned as p1 = p2;
func2(p1); //in this function, p1 is assigned to another pointer: int * p3 = (int *)p1;
then, i called func3 to release the memory
func3(p1); //delete int * p1
after calling func3, do i have to deal with p2 in func1 anymore?
thanks!
Yes, all 3 delete
s are equivalent. It's important to note that in the posted example, all 3 pointers point to the same thing. This means if you delete
one of them, you should not delete
the others as the memory they point to has already been released.
If you do try to delete
something that has already been released, you'll evoke Undefined Behavior. If you're lucky your program will crash, but anything could happen.
The question contains a misconception: you don't delete the pointers. You delete what they point to.
And you cannot delete a same thing more than once.
Think to three people pointing their fingers towards a same box. One of them says "throw it away". Once it has been thrown, they will remain with their finger still pointing in the same direction towards an empty space. With nothing more to throw away.
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