How to use delete with a variable pointed to by two pointers?

走远了吗. 提交于 2019-12-23 12:54:37

问题


Let say I have a hypothetical pointer declared with new like so:

int* hypothetical_pointer = new int;

and create another hypothetical pointer, with the same value:

int* another_hypothetical_pointer = hypothetical_pointer;

If I were to go about deleting these, which were declared with new, would I have to delete both pointers, or only the one explicitly declared with new? Or could I delete either pointer?


回答1:


delete destroys the dynamically allocated object pointed to by the pointer. It doesn't matter if there are one or 100 pointers pointing to that object, you can only destroy an object once.

After you delete hypothetical_pointer;, you cannot use hypothetical_pointer or another_hypothetical_pointer because neither of them points to a valid object.

If you need to have multiple pointers pointing to the same object, you should use a shared-ownership smart pointer, like shared_ptr, to ensure that the object is not destroyed prematurely and that it is destroyed exactly once. Manual resource management in C++ is fraught with peril and should be avoided.




回答2:


There is only one block of memory from the single call to new, so you must delete it once and only once, when all users are done with it.

boost::shared_ptr is a nice way to accommodate multiple users of the same data - the last reference going out of scope triggers delete on the underlying memory block.

boost::shared_ptr<int> ptr1(new int);
boost::shared_ptr<int> ptr2(ptr1);

// memory deleted when last of ptr1/ptr2 goes out of scope



回答3:


Only call delete on one of those pointers - doesn't matter which, since they both contain the same value, as a pointer. Do not use either pointer after calling delete.




回答4:


Correct answer is that you don't delete either. You delete what they point at.

Now...if they both point at the same thing, how many times do you think you should delete what they point at?



来源:https://stackoverflow.com/questions/4392546/how-to-use-delete-with-a-variable-pointed-to-by-two-pointers

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