I have this very simple code:
#include <iostream>
using namespace std;
int main()
{
int *p, *q, u;
{
p = new int(4);
int v = 5;
q = &v;
u= v;
}//End scope 2
cout<< *p << "\n" << *q << "\n" << u;
delete p;
return 0;
}
And the output is:
4
5
5
Pleaso cerrect me if I'm wrong :) ...
- if I understand,
p
is pointing to a memory space that was allocated in the heap, this memory won't be affecetd at the "end scope" and will only be dellocated when callingdelete
. - Then
u
is a hard copy ofv
, so there's actually a copy of it's value somewhere else in the stack memory. - On the other hand
q
points to the address ofv
, which is allocated in the stack and should be erased (?) when leaving the "scope 2", if this is the case, why printing*q
still finds the right value ofv
?