Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing item from list of weak_ptrs

Tags:

c++

pointers

I have a list of weak_ptrs that I'm using to keep track of objects. At a certain point, I would like to remove an item from the list given a shared_ptr or a 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 won't 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 do I remove an item from the list given a shared_ptr or a weak_ptr?

like image 763
user987280 Avatar asked Apr 12 '12 09:04

user987280


People also ask

Is weak_ptr thread safe?

Using weak_ptr and shared_ptr across threads is safe; the weak_ptr/shared_ptr objects themselves aren't thread-safe.

Can weak_ptr be copied?

std::weak_ptr are pointers, so as with any pointer types, a = p; copy pointer, not the content of what is pointed. If you want to copy the content, you would need *a = *p; , but you cannot do that with weak_ptr , you need to lock() both a and p before.

Can a weak_ptr point to a Unique_ptr?

You can implement weak_ptr which works correctly with unique_ptr but only on the same thread - lock method will be unnecessary in this case.

How can a weak_ptr be turned into a shared_ptr?

The weak_ptr class template stores a "weak reference" to an object that's already managed by a shared_ptr. To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock.


Video Answer


1 Answers

There is no operator== for weak pointers. You could compare the shared_ptrs your weak_ptrs point to.
E.g like this.

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;
});
like image 146
mkaes Avatar answered Oct 20 '22 22:10

mkaes