从weak_ptrs列表中删除项目

removing item from list of weak_ptrs

本文关键字:删除项目 列表 ptrs weak      更新时间:2023-10-16

我有一个用于跟踪对象的weak_ptrs列表。在某个时候,我想从给定shared_ptr或weak_ptr的列表中删除一个项目。

#include <list>
int main()
{
typedef std::list< std::weak_ptr<int> > intList;
std::shared_ptr<int> sp(new int(5));
std::weak_ptr<int> wp(sp);
intList myList;
myList.push_back(sp);
//myList.remove(sp);
//myList.remove(wp);
}

但是,当我取消注释上述行时,程序不会构建:

1>c:program files (x86)microsoft visual studio 10.0vcincludelist(1194): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::tr1::weak_ptr<_Ty>' (or there is no acceptable conversion)

如何在给定shared_ptr或weak_ptr的情况下从列表中删除项目?

弱指针没有运算符==。您可以比较weak_ptrs指向的shared_ptrs。
比如这样。

myList.remove_if([wp](std::weak_ptr<int> p){
    std::shared_ptr<int> swp = wp.lock();
    std::shared_ptr<int> sp = p.lock();
    if(swp && sp)
        return swp == sp;
    return false;
});