Std :: shared_ptr with std containers

I have a shared_ptr container and I pass these window API objects and I get a callback later with raw ptr. I want to find the correct shared_ptr after the fact. Can this be done using shared_ptr? (without using shared_from_this() ).

very simple example:

 class CFoo { }; typedef std::shared_ptr<CFoo> CFooPtr; typedef std::set<CFooPtr> CFooSet; extern CFooSet m_gSet; void SomeWindowsCallBack(CFoo* pRawPtr) { m_gSet.erase(pRawPtr); } 

I know that this can be done with intrusive_ptr very easily, but I'm curious if there is a way with shared_ptr . Aka I'm looking for a container to accept RawPtr and shared_ptr to search for the shared_ptr element. The problem is that I cannot implicitly use CFoo* in shared_ptr (for reasons I understand).

I thought I could do

m_gSet.erase(shared_ptr<CFoo>(pRawPtr, _do_not_delete_deleter))

but I have not tried it yet and it seems dangerous / ugly. Is there any other way or am I mostly looking for intrusive_ptr ? Thanks

+4
source share
1 answer

Why not the obvious way? Iterate through the container and

 if(iterator->get() == rawPointer) container.erase(iterator) 

Edit: To use O (logN) lookup, you can do what you want (i.e. create shared_ptr with no_op deleter). It may be ugly, but it is not dangerous

+2
source

Source: https://habr.com/ru/post/1342861/


All Articles