我正在看这里,其中m_Rows是一个CAtlList:
void CData::RemoveAll()
{
size_t cItems = m_Rows.GetCount();
POSITION Pos = m_Rows.GetHeadPosition();
while(Pos != 0)
{
CItem* pItem = m_Rows.GetAt(Pos);
if (pItem != 0)
delete pItem;
POSITION RemoveablePos = Pos;
pItem = m_Rows.GetNext(Pos);
m_Rows.RemoveAt(RemoveablePos);
}
}
并且想知道RemoveAt调用是否有可能使Pos失效?
最佳答案
根据documentation,CAtlList的行为类似于双向链接列表,因此删除一个列表项不应使指向其他项的指针无效。 POSITION
类型直接引用列表项的存储位置:
在atlcoll.h中似乎并非如此:
template< typename E, class ETraits >
void CAtlList< E, ETraits >::RemoveAt( POSITION pos )
{
ATLASSERT_VALID(this);
ATLENSURE( pos != NULL );
CNode* pOldNode = (CNode*)pos;
// remove pOldNode from list
if( pOldNode == m_pHead )
{
m_pHead = pOldNode->m_pNext;
}
else
{
ATLASSERT( AtlIsValidAddress( pOldNode->m_pPrev, sizeof(CNode) ));
pOldNode->m_pPrev->m_pNext = pOldNode->m_pNext;
}
if( pOldNode == m_pTail )
{
m_pTail = pOldNode->m_pPrev;
}
else
{
ATLASSERT( AtlIsValidAddress( pOldNode->m_pNext, sizeof(CNode) ));
pOldNode->m_pNext->m_pPrev = pOldNode->m_pPrev;
}
FreeNode( pOldNode );
}