c++ - 从 weak_ptr 列表中删除项目

标签 c++ pointers

我有一个用于跟踪对象的 weak_ptr 列表。在某个时候,我想从给定 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.0\vc\include\list(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_ptr 指向的 shared_ptr。
例如像这样。

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

关于c++ - 从 weak_ptr 列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10120623/

相关文章:

c++ - 使用 RapidXML/C++ 类指针副作用进行解析时的递归问题

c++ - Strcat,2 个字符指针数组

c++ - 何时在组合上使用 C++ 私有(private)继承?

c++ - 使用 Boost Spirit Classic 解析 SQL INSERT

c++ - 编译和使用 OpenCV

c++ - cudaMemcpy 段错误

c - 给定 `int num[7]` , `num` 、 `&num[0]` 、 `&num` 有何不同?

c++ - 检测视频流上的几何对象并重建其轮廓

c++ - 在 C++ 中,如何使用类成员来保存从基类派生的任何对象?

混淆 C 指针行为