通过其值的指针从列表中删除unique_ptr

时间:2014-07-08 16:03:10

标签: c++ list pointers unique-ptr

给定指向对象的指针,我试图从unique_ptrs列表中删除相同的对象。我这样做是通过匹配较大list列表的原始指针unique_ptr子集的每个元素来实现的,该列表肯定包含子集list中的所有元素。代码:

编辑:为清楚起见,rawListSubset为std::list<MyObj> 和smartListSet是std::list< unique_ptr<MyObj> >

for (auto& deleteThis : rawListSubset)
{
    // Find the matching unique_ptr
    for (auto& smartPtrElement : smartListSet)
    {
        if (deleteThis == smartPtrElement.get()) 
        { 
            unique_ptr<Entity> local = move(smartPtrElement); 
            // Hence deleting the object when out of scope of this conditional
        }
    }
}

或者,这不起作用,但它提出了我正在尝试做的事情。

for (auto& deleteThis : rawListSubset)
{
    // Find the matching unique_ptr
    for (auto& smartPtrElement : smartListSet)
    {
        if (deleteThis == smartPtrElement.get()) 
        {

            smartListSet.remove(smartPtrElement);
            // After this, the API tries to erroneously copy the unique_ptr

        }
    }
}

如何删除指针指向的对象,并将其从列表中安全删除?

2 个答案:

答案 0 :(得分:3)

要从循环中的std::list安全地删除元素,必须使用迭代器。 std::list::erase()删除迭代器指定的元素,并将迭代器返回到列表中的下一个元素:

for (auto& deleteThis : rawListSubset)
{
    // Find the matching unique_ptr
    auto i = smartListSet.begin();
    auto e = smartListSet.end();
    while (i != e)
    {
        if (deleteThis == i->get()) 
            i = smartListSet.erase(i);
        else
            ++i;
    }
}

答案 1 :(得分:1)

您可以通过使用迭代器迭代列表来删除元素,而不是使用范围循环:

for (auto& deleteThis : rawListSubset)
{
    // Find the matching unique_ptr
    for (auto smartPtrIter = smartListSet.begin(); smartPtrIter != smartListSet.end(); )
    {
        if (deleteThis == smartPtrIter->get()) 
        {

            smartListSet.erase(smartPtrIter++);
        } else
            ++smartPtrIter;
    }
}

当您从列表中删除该元素时,智能指针指向的对象将被删除,即智能指针的用途。

相关问题