繁体   English   中英

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

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

给定一个指向对象的指针,我试图从unique_ptrs列表中删除同一对象。 我通过匹配更大的unique_ptr列表的原始指针list子集的每个元素来做到这一点,该列表肯定包含子集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

        }
    }
}

如何既删除指针所指向的对象,又将其安全地从其列表中删除呢?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM