開(kāi)發(fā)中發(fā)現(xiàn)在進(jìn)行 賦值操作的時(shí)候,很容易內(nèi)存丟失,看實(shí)例:
class CEntity
{
public:
CEntity(char flag);
~CEntity();
private:
char m_flag;
};
CEntity::CEntity(char flag)
{
m_flag = flag;
cout<<"constructing entity "<<m_flag<<endl;
}
CEntity::~CEntity()
{
cout<<"destructing entity "<<m_flag<<endl;
}
執(zhí)行代碼:
int main(int argc, char* argv[])
{
CEntity m('m'),n('n');
m = n;
return 0;
}
輸出為:
constructing entity m
constructing entity n
destructing entity n
destructing entity n
這個(gè)沒(méi)有出現(xiàn)任何問(wèn)題,很成功,因?yàn)樵贑Entity里面沒(méi)有new任何東西,如果把CEntity該為:
class CEntity
{
enum {SIZE = 10};
public:
CEntity(char flag);
~CEntity();
private:
char * m_flag;
};
CEntity::CEntity(char flag)
{
m_flag = new char[SIZE ];
m_flag[0] = flag;
cout<<"constructing entity "<<m_flag[0]<<endl;
}
CEntity::~CEntity()
{
cout<<"destructing entity "<<m_flag[0]<<endl;
delete[] m_flag;
}
執(zhí)行同樣的main函數(shù),程序?qū)o(wú)法運(yùn)行,debug assertion error!
這個(gè)問(wèn)題該怎么解決? 先睡覺(jué)
如oosky所說(shuō),重載了賦值操作符,問(wèn)題就解決了,
CEntity & CEntity::operator=(const CEntity & ent)
{
if (ent.m_flag == NULL)
{
if (m_flag != NULL)
{
delete [] m_flag;
m_flag = NULL;
}
}
else
{
if (m_flag == NULL)
{
m_flag = new char[SIZE];
}
for(int i=0; i<SIZE; i++)
{
m_flag[i] = ent.m_flag[i];
}
}
return *this;
}
由此可見(jiàn)自定義對(duì)象之間的賦值操作要小心行事.....