Does deleting a pointer delete the memory it's pointing too?

 ̄綄美尐妖づ 提交于 2020-01-01 04:44:28

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11855306/does-deleting-a-pointer-delete-the-memory-its-pointing-too

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!