In C and C++, a pointer can be thought of in many ways as just an integer in disguise. So when you say:
TheObject *ptr = new TheObject;
Then ptr
is just like a stack-allocated ("automatic") integer variable, one that happens to be big enough to hold the memory address of the heap-allocated TheObject
. It's similar to saying
size_t i = /* some value given to you by the runtime */.
Later on, when you write
ptr = NULL;
it has an identical meaning to:
i = 0;
So what happens to the pointer when you leave the function? Just as with any other automatic variable, it's deallocated at the end of the block. It's as simple as that. (Of course, the thing that's pointed to will live on until you call delete
, or free()
in C.)