Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort order of boost::weak_ptr after expiring?

For boost::weak_ptr the operator< is defined, so that it can be used in associative containers.

My question is: Is the sort order of several weak_ptr objects stable even when some of them change to a refcount of zero? Doesn't that mess with containers like std::set?

Example:

using namespace boost;
shared_ptr<A> sptrA1(new A);
weak_ptr<A> wptrA1 = sptrA1;
weak_ptr<A> wptrA2;

{ // begin Scope 1
    shared_ptr<A> sptrA2(new A);
    wptrA2 = sptrA2;
    assert(wptrA1 < wptrA2); // assert #1
}
assert(wptrA1 < wptrA2); // assert #2
  • Will assert #2 always hold true if assert #1 is true?
  • Is wptrA2 in the same state before and after the Scope 1?
like image 890
Hanno S. Avatar asked Jan 21 '11 17:01

Hanno S.


3 Answers

In the current implementation of boost::weak_ptr, operator< compares a pointer to an internal reference-count-tracking structure. This structure is not freed until all strong and weak references are removed, so it remains safe to use operator< even if the pointed-to user data has been freed due to a lack of strong references.

like image 144
bdonlan Avatar answered Sep 18 '22 13:09

bdonlan


Read about weak_ptr comparision here.

like image 22
Öö Tiib Avatar answered Sep 21 '22 13:09

Öö Tiib


Use std::owner_less. This compares the pointer of the use count, not the pointer itself. For example:

typedef std::weak_ptr<int> IntWPtr;
std::set<IntWPtr, std::owner_less<IntWPtr> > m_set;
like image 32
tgoodhart Avatar answered Sep 20 '22 13:09

tgoodhart