I'm trying to understand exactly what happens to deleted variables in c++. Let's say I have something like the following.
MyObject * obj;
for (int i = 0; i < 100000000; i++){
obj = someMethodThatReturnsNewMyObject();
obj->doSomething();
delete obj;
}
Now, upon instantiation, obj
is a pointer to a MyObject
object. It is first initialized by the line obj = someMethodThatReturnsNewMyObject();
. Then some method is called just for fun, and obj
is deleted. Now I know when something is deleted like this, the memory space that it is pointing to is expunged, and the pointer is set to point an nothing.
But, then when the for loop comes back around, I re-initialize the pointer, causing it to allocate a new memory space and obj
then points at this new space instead. But, at no point was the pointer itself removed from memory. Throughout the loop it only ever points at whatever I tell it to point to or points at nothing (upon deletion).
My question then, is this: When does the pointer itself, that is, the memory space taken up by the pointer, get deleted and why is it not under my requirements to have to delete that if I am required to delete the memory pointed at?