新人一个链表类的问题,为什么会出现内存泄漏
template <class T>
class CDListNode
{
public:
friend CDList <T> ;
private:
T data;
CDListNode <T> * previous;
CDListNode <T> * next;
};
template <class T>
class CDList
{
private:
CDListNode <T> * m_phead;
CDListNode <T> * m_ptail;
int m_count;public:
CDList();
~CDList();
int AddTail(const T & NewNode);
void RemoveAll(void);
T & GetAt(int position) const;
int GetCount(void) const;
bool IsEmpty(void) const;
};
template <class T>
CDList <T> ::CDList():m_phead(NULL), m_ptail(NULL), m_count(0)
{
}
template <class T>
CDList <T> ::~CDList()
{
RemoveAll();
}
//从链表尾部插入结点
template <class T>
int CDList <T> ::AddTail(const T & NewNode)
{
CDListNode <T> *p;
p = new CDListNode <T> ;
p-> data = NewNode;p-> next = NULL;
if (m_ptail == NULL)// 链表为空
{
p-> previous = NULL;
m_phead = p;
}
else
{
p-> previous = m_ptail;
m_ptail-> next = p;
}
m_ptail = p;
m_count++;return (m_count-1);
}// 删除所有结点
template <class T>
void CDList <T> ::RemoveAll(void)
{
if (IsEmpty()) return;
CDListNode <T> *p = m_phead;
while (m_phead != NULL)
{
m_phead = m_phead-> next;
delete p;
p = m_phead;
m_count--;
}
m_ptail = NULL;
}
// 获取结点值
template <class T>
T & CDList <T> ::GetAt(int position) const
{
assert((position> =0) && (position <m_count));CDListNode <T> *p = m_phead;
for (int i=0; i <position; i++) // 定位结点
{
p = p-> next;
}
return p-> data;
}
// 获取链表结点个数
template <class T>
int CDList <T> ::GetCount(void) const
{
return m_count;
}
main()
{
CDList < CDList <AnsiString> > *pDataList ;
pDataList = new CDList < CDList <AnsiString> > ;
CDList < AnsiString > pData;
pData.Add( "111 ");
pDataList-> Add(pData);
delete pData;
}
我调试了下,发现在pDataList-> Add(pData)这里执行完之后对pData执行了2次removeall导致了内存泄漏
请问下这个该怎么解决
[解决办法]
这个CDList < AnsiString > pData; 你后面的delete pData居然可以编译通过?
------解决方案--------------------
CDList < CDList <AnsiString> > *pDataList ;
pDataList = new CDList < CDList <AnsiString> > ;
...为何只见new,未见delete!
[解决办法]
因为void CDList <T> ::RemoveAll(void)
CDList < CDList <AnsiString> > *pDataList // T = CDList <AnsiString>
//CDList <AnsiString> 的T=AnsiString
执行delete pDataList 时,会调用pDataList.removeall;
在释放pData时又会执行一次pData.removeall
所以是2次了