Question

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?
Was it helpful?

Solution

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.

OTHER TIPS

Read about weak_ptr comparision here.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top