I have the following code
class Test
{
public:
int &ref;
int a;
Test(int &x)
:ref(x)
{
cout<<"Address of reference "<<&ref<<endl;
cout<<"&a : "<<&a<<endl;
cout<<"this = "<<this<<endl;
}
};
int main()
{
Test *pObj = NULL;
{
int i = 10;
cout<<"Address of referent "<<&i<<endl;
pObj = new Test(i);
}
pObj->ref++;
cout<<pObj->ref;
}
Output:
Address of referent 002DFB3C
Address of reference 002DFB3C
&a : 00734C94
this = 00734C90
As you can see, the test object is created dynamically. the i variable, which is stored on the stack, is sent as a parameter to the constructor of the Test class. I typed the address of the variables i, ref and a.
Question: the variable I will be destroyed after the program control leaves the block in which it is declared. But the dynamically assigned member variable of the ref object will still refer to the stack address (address i). You can use ref after death i.
Why does the heap object refer to the stack stack? Why is this allowed?
source
share