开发中发现在进行 赋值操作的时候,很容易内存丢失,看实例:
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;
}
由此可见自定义对象之间的赋值操作要小心行事.....