Link to home
Start Free TrialLog in
Avatar of lbalan791
lbalan791

asked on

Simple question about CLists

How can I prevent memory leaks in a list of pointers when objects are created and added like this:

void CMyClass::MyFunction()
{
  CMyMsg *pMsg = new CMyMsg;
  ASSERT(pMsg);
  //work with pMsg
  .....
  m_MsgList.Addtail(pMsg);
}
where m_MsgList is a member of CMyClass and is defined like this:

CList<CMyMsg *, CMyMsg*>m_MsgList;

If I write delete pMsg; at the of the function the information in m_MsgList is also deleted. If I don't delete pMsg obviously memory leaks appear... Please help...
Avatar of bistrica
bistrica

delete each pointer first, when clearing

m_MsgList.Addtail

like:

int size = m_MsgList.getsize();
for (int i =0;i<size;i++)
{
   delete m_MsgList[i];
}

m_MsgList.removeall();
ASKER CERTIFIED SOLUTION
Avatar of williamcampbell
williamcampbell
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial