变量调用其他变量销毁自己
#include <iostream>
using namespace std;
class Child;
class Father
{
public:
void DelChild(Child *p);
};
class Child
{
public:
void fun()
{
m_p->DelChild(this);
char *ch=this->getName();
cout<<ch<<endl;
};
char* getName(){return "111222";};
Child(Father *p)
{
m_p=p;
strcpy(m_ch,"111222");
}
~Child()
{
cout<<"destory"<<endl;
}
Father* m_p;
char m_ch[10];
};
void Father::DelChild(Child *p)
{
delete p;
}
int main()
{
Father* pf=new Father;
Child* child=new Child(pf);
child->fun();
return 0;
}
结果:
destory
111222
Press any key to continue
#include <iostream>
using namespace std;
class Child;
class Father
{
public:
void DelChild(Child *p);
};
class Child
{
public:
void fun()
{
m_p->DelChild(this);
char *ch=this->getName();
cout<<ch<<endl;
};
char* getName(){return m_ch;};
Child(Father *p)
{
m_p=p;
strcpy(m_ch,"111222");
}
~Child()
{
cout<<"destory"<<endl;
}
Father* m_p;
char m_ch[10];
};
void Father::DelChild(Child *p)
{
delete p;
}
int main()
{
Father* pf=new Father;
Child* child=new Child(pf);
child->fun();
return 0;
}
结果:
destory
葺葺葺葺葺葺葺葺
Press any key to continue
个人理解:
虽然变量已经销毁,但是代码区还存在