How to get raw_ptr based element from unordered_set with key on shared_ptr

I am wondering if in any case there is an element for me based on its raw pointer, with unordered_seta key 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()));
+4
source share
2 answers

You can declare MyObjas:

class MyObj : public std::enable_shared_from_this<MyObj>
{
     ....
}

This adds a method that returns a generic pointer for a given instance of the object.

MyObj * rawptr = myobj.get();
sets.find(rawptr->shared_from_this());

Please note that before the call, the shared_from_this()object must be std::shared_ptrto which it belongs.

-1
source

, , , std:: set .

, unordered_set. ( , ), shared_from_this() alexm. - .

-

, .

:

struct Raw_comp{
  using is_transparent = std::true_type;
  bool operator()(const shared_ptr<MyObj>& lhs, const shared_ptr<MyObj>& rhs) const{
   return lhs < rhs;
}
  bool operator()(shared_ptr<MyObj>& lhs, MyObj* rhs) const{
   return std::less<MyObj>()(lhs.get(), rhs);
}
  bool operator()(const MyObj* lhs, const shared_ptr<MyObj>& rhs) const{
   return std::less<MyObj>()(lhs, rhs.get());
}
};

:

set< shared_ptr<myObj>, Raw_cmp> sets;

​​ ,

+3

All Articles