How to use delete with a variable pointed to by two pointers?
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 explici开发者_JAVA百科tly declared with new? Or could I delete either pointer?
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.
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
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
.
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?
精彩评论