我有一个用于跟踪对象的 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/