When you have an object, it will be in some place in memory. This value is for both n1 and n2 . When you delete an object, freeing up the memory that this object uses, the memory is invalid. Thus, you can never access those points n1 if they were deleted.
I suggest creating a wrapper object containing a counter and a pointer to the object. When you want to point to the actual object, you must point to the shell instead, and when you want to delete the object, you actually call the method on the wrapper:
If you want to point to an object, you must increase the wrapper counter and point to the wrapper. If you want to delete an object, you must decrease the counter and set the pointer to the wrapper to null. If the wrapper counter reaches zero, you can safely delete the actual object and then the wrapper.
source share