When this method exits (returns 0), does it destroy the variable x?
Yes. x
has automatic storage duration, and is destroyed when it goes out of scope - in this case, when the function returns.
And is this variable stored in the stack or the heap?
On the stack.
I know for example you could do
int *x = new int(99)
, and then it would be in the heap.
Indeed; the object created by new
has dynamic storage duration, and is on the heap. Note that there's a second object x
, a pointer to the object on the heap. x
itself is an automatic object on the stack. (Pedantically, C++ calls the source of dynamic memory the "free store", not the "heap").
But without the
*
, is it inside the stack?
Without the *
, that wouldn't compile. new
creates an object in memory taken from the heap, and gives the address of it. *
indicates that x
is a pointer, so can hold that address. Without it, it would be int
and couldn't hold the address.
And in the above method, when it exits, is x destroyed?
The pointer x
is; but the object it points to is not. Dynamic objects (created with new
) last until they are explicitly destroyed with delete
. If that never happens, then you have a memory leak - memory was allocated but never released.
Avoid dynamic allocation unless you really need it; and when you do, always use smart pointers, containers, etc. to manage it safely, and avoid using new
and juggling raw pointers.