開發中發現在進行 賦值操作的時候,很容易內存丟失,看實例:
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;
}
執行代碼:
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
這個沒有出現任何問題,很成功,因為在CEntity里面沒有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;
}
執行同樣的main函數,程序將無法運行,debug assertion error!
這個問題該怎么解決? 先睡覺
如oosky所說,重載了賦值操作符,問題就解決了,
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;
}
由此可見自定義對象之間的賦值操作要小心行事.....