Removing an item from the weak_ptrs list

I have a list of weak_ptrs that I use to track objects. At some point, I would like to remove an item from the list using shared_ptr or 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); } 

However, when I uncomment the above lines, the program will not build:

 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) 

How to remove an item from a list using shared_ptr or weak_ptr?

+7
source share
1 answer

For weak pointers, there is no == operator. You can compare share_ptrs with your weak_ptrs value. For example, for example.

 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; }); 
+6
source

All Articles