从 std::list 中删除元素 std::unique_pointer

Removing an element from std::list of std::unique_pointer

根据这个线程 Returning a pointer to a vector element ,建议在将对象插入向量并返回其指针时使用以下代码:

// in your class
std::vector<std::unique_ptr<SceneGraphNode>> m_children;

SceneGraphNode* addChild(std::string name)
{
    std::unique_ptr<SceneGraphNode> child(new SceneGraphNode(this,name));
    myList.push_back(std::move(child));
    return myList.back().get();
}

我打算使用相同的代码,但带有 std::list。那时我没有重新分配的问题,但是 std::unique_ptr 仍然有助于破坏向量 - 而不是普通的 delete.

问题:如何在此设置中使用列表的 remove?使用普通指针,我可以只写 myList.remove(myPtr),其中 myPtr 是指向要删除的对象的普通指针。

如果 myPtrunique_ptr,您仍然可以执行 myList.remove(myPtr)。这是因为 operator== 为这样的智能指针重载:http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_cmp

这样的内容可能会有帮助:

it = find(myList.begin(), myList.end(), name);
if (it != myList.end())
{
   mylist.erase(it);
}

如果你真的想使用普通指针作为 myPtr,你可以使用

myList.remove_if([myPtr](const std::unique_ptr<SceneGraphNode>& ptr){return ptr.get() == myPtr});