is that how it works?
Not quite. First, you have undefined behavior, you can't delete an object with automatic storage (for example, on the stack).
Let's change your example to that:
int* ptrA = new int{10};
int* ptrB = ptrA;
delete ptrB;
return 0;
but then we have 2 pointers which are pointing to a valid address , whose data has just been deleted ?
Well, both. There are two pointer indeed, pointing to the same value.
If you print the value of ptrA
and ptrB
, you'll see something similar to that:
0x0034ab56
0x0034ab56
Both pointers point to the same address in memory.
So in other words, if you delete ptrA
, you will deallocate the object at address 0x0034ab5
. Since both pointers point to the same address, both pointer are now dangling. The official term for it is an invalid pointer value, and both ptrA
and ptrB
are invalid pointer values because the storage which both pointer were pointing to has been freed.