Search code examples
c++pointersnew-operatordelete-operator

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 explicitly declared with new? Or could I delete either pointer?


Solution

  • 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.