本文介绍了CAtlList::RemoveAt 是否会使现有位置无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看这个,其中 m_Rows 是一个 CAtlList:

I'm looking at this, where m_Rows is a 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 失效?

and am wondering if there's potential that the RemoveAt call may invalidate Pos?

推荐答案

根据 文档,CAtlList 的行为类似于双链表,因此删除一个列表项应该不会使指向其他项的指针无效.POSITION 类型直接引用列表项的内存位置:

According to the documentation, CAtlList behaves like a double linked list, so removing one list item should not invalidate the pointers to other items. The POSITION type references the memory location of a list item directly:

大多数 CAtlList 方法使用位置值.方法使用此值来引用存储元素的实际内存位置,不应直接计算或预测.

在 atlcoll.h 中似乎不是这种情况:

It seems this is not the case in 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 );
}

这篇关于CAtlList::RemoveAt 是否会使现有位置无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 23:57