If I have a pointer like so:
int *test = new int;
And I create another pointer that points to test
like so:
int *test2 = test;
Then I delete test2
:
delete test2;
Does that mean that it will delete the memory of test
as well, or would I have to call delete test
also?
You never delete the memory for test
, nor do you delete the memory for test2
. The only thing that ever gets deleted is the object *test
, which is identical to the object *test2
(since the pointers are the same), and so you must only delete it once.
This is a very common and very unfortunate misnomer that propagates and spoils the minds of people new to C++: One often speaks colloquially of "freeing a pointer" or "deleting a pointer", when you really mean "freeing memory to which I have a pointer", or "deleting an object to which I have a pointer". It's true that the relevant constructions (i.e. std::free
and delete
) take as their argument a pointer to the entity in question, but that doesn't mean that the pointer itself is operated on -- it merely communicates the location of the object of interest.
Yes, the memory will be deleted freed as both pointers point to the same memory.
Furthermore, test
will now be a dangling pointer(as will test2
) and dereferencing it will result in undefined behaviour.
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