Welcome to ErranLi's Blog!

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  106 Posts :: 1 Stories :: 97 Comments :: 0 Trackbacks

常用链接

留言簿(12)

搜索

  •  

积分与排名

  • 积分 - 169363
  • 排名 - 151

最新评论

阅读排行榜

开发中发现在进行 赋值操作的时候,很容易内存丢失,看实例:

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;
}

由此可见自定义对象之间的赋值操作要小心行事.....

 

posted on 2006-05-21 00:47 erran 阅读(766) 评论(5)  编辑 收藏 引用 所属分类: C & C++

Feedback

# re: C++随笔 关于赋值操作 内存丢失 2006-05-21 14:27 oosky
m = n;
操作执行了默认的赋值函数,两个对象都指向同一块地址,然后析构的时候对同一地址delete两次,并且在赋值的时候丢失了一块内存,造成了内存泄露。
所以自己写赋值函数,才能解决问题。  回复  更多评论
  

# re: C++随笔 关于赋值操作 内存丢失 2006-05-22 16:38 任我行
CEntity & CEntity::operator=(const CEntity & ent)
你的这个函数还是有问题。
else
{
if (m_flag == NULL)
{
m_flag = new char[SIZE];
}
在这里。
m_flag!=NULL的时候直接m_flag = NULL就造成了内存泄漏,原来的m_flag指向的内存丢失。
if(m_flag != NULL) delete []m_flag;
m_flag = new char[size];

  回复  更多评论
  

# re: C++随笔 关于赋值操作 内存丢失 2006-05-22 21:10 erran
没看出来,好想没问题吧,是不是看错了  回复  更多评论
  

# re: C++随笔 关于赋值操作 内存丢失 2006-05-23 08:53 任我行
嗯,是看错了.
CEntity & CEntity::operator=(const CEntity & ent)
{
if(m_flag != NULL){
delete []m_flag;
m_flag = NULL;
}
if(ent.m_flag!=NULL)
memcpy(m_flag, ent.m_flag, SIZE);
return *this;
}  回复  更多评论
  

# re: C++随笔 关于赋值操作 内存丢失[未登录] 2008-08-28 12:56 Henry
可以定义一个拷贝构造函数试试  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理