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

Removing a unique_ptr from a list, by its value's pointer

本文关键字:列表 删除 指针 unique ptr 通过      更新时间:2023-10-16

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

编辑:为了清晰起见,rawlist子集是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
        }
    }
}

如何既可以删除指针指向的对象,又可以安全地从其列表中删除它?

要安全地从循环中的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;
    }
}

可以使用迭代器遍历list来删除元素,而不是使用范围循环:

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;
    }
}

当你从列表中删除智能指针所指向的元素时,智能指针所指向的对象将被删除。