Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a boost::shared_ptr as a key for a map?

I may need to rethink my overall design a bit more, but as it stands, it looks like I may want to do something like:

class A; 
class B;
std::map<boost::shared_ptr<const A>, B> APtrToBMap;

I've tried this, and it does seem to work in a simple case (the compiler didn't complain, and simple tests seem to work). But I'm having second thoughts about this approach. I suspect there are some gotchas in there that I'm not aware of.

So, is the above valid in a practical sense? Or is there some flaw I'm not aware of when I do this?

like image 719
Taeolas Avatar asked Nov 10 '10 15:11

Taeolas


Video Answer


1 Answers

The reference has this to say:

template<class T, class U>
  bool operator<(shared_ptr<T> const & a, shared_ptr<U> const & b); // never throws

Returns: an unspecified value such that

  • operator< is a strict weak ordering as described in section 25.3 [lib.alg.sorting] of the C++ standard;
  • under the equivalence relation defined by operator<, !(a < b) && !(b < a), two shared_ptr instances are equivalent if and only if they share ownership or are both empty.

Throws: nothing.

Notes: Allows shared_ptr objects to be used as keys in associative containers.

like image 136
UncleBens Avatar answered Oct 22 '22 18:10

UncleBens