Say I have two classes created work and workItem.
CWorker *work = new CWorker();
CWorkItem *workItem = new CWorkItem();
The work class has a public list m_WorkList and I add the work item to it.
work->m_WorkList.push_back(workItem);
If I just delete work
if(work != NULL)
delete work;
Do I need to loop through the list in the destructor like the following? Any better way to do this? Could I use clear instead?
while(m_WorkList.size())
{
CWorkItem *workItem = m_WorkList.front();
m_WorkList.pop_front();
if(workItem)
delete workItem;
}
Yes you need to
deleteeach item. If you callnewN times, then you need to calldeleteexactly N times as well. There is no shortcut for bulk deleting items.Also when you’re done with it you need to call
deleteonwork.You can use
new[]anddelete[]if you want to create an array of items on the heap and release the items on the heap respectively at once. But in your case this isn’t what you’re looking for.You can look to boost::shared_ptr if you don’t want to manually do these delete calls.