I am wondering if there is anyway for me to retrieve an element based on its raw pointer from an unordered_set
keyed on shared_ptr
.
unordered_set< shared_ptr<MyObj> > sets;
auto myobj = make_shared<MyObj>();
sets.insert(myobj);
// Find the element myobj
sets.find(myobj);
// How to find the element based on the underlying raw pointer?
sets.find(my.obj.get()); <---- apparently this gives compile error
// This method works but it will double free myobj though (not correct)
sets.find(shared_ptr<MyObj>(my.obj.get()));
You can declare MyObj
as:
class MyObj : public std::enable_shared_from_this<MyObj>
{
....
}
This adds a method returning a shared pointer for a given object instance.
MyObj * rawptr = myobj.get();
sets.find(rawptr->shared_from_this());
Note that prior to calling shared_from_this()
on an object, there must be a std::shared_ptr
that owns it.