Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-07-22 09:35:03


Jason Winnebeck wrote:
> Is there a reason why weak_ptr's cannot be compared with ==, or tested
> in a conditional?
>
> If I have two weak_ptr's, I thought it to be strange that I have to
> do:
>
> (w1.lock() == w2.lock())

This comparison is well defined (even though the results you get may no
longer be true if w1 or w2 is invalidated after the comparison) because the
two lock() calls create two shared_ptr temporaries that "lock" the objects
against deletion until operator== is evaluated.

The general problem with weak_ptr is that its pointer can be invalidated at
any time, and accessing its value would then be undefined behavior.

A w1 == w2 shortcut is not provided since this kind of comparison isn't
needed frequently and due to the subtleties involved.

> And to test if a weak_ptr is the empty weak_ptr:
>
> if ( !(w1.lock()) )
>
> which seems kind of awkward.

Why do you want to test w1 without also doing something with it?

[...]

> I would like the semantics that w1 and w2 compare to be equal whether
> or
> not the object they are pointing to are valid or not. I'm not sure if
> weak_ptrs become "empty" when the object they point to is destroyed
> (because there's no way to test for "emptyness" or "nullness" of a
> weak_ptr), but if they do I can see how the equality test can't work,
> but not the conditional test.

The comparison you want is spelled !(w1 < w2) && !(w2 < w1), but why do you
need it?

[...]

> Is it acceptable (the documentation didn't make it clear to me), to
> use
>
> if ( w1.expired() )
>
> to test if simply if w1 is "null" or "reset".

Yes, w1.expired() is an alias for w1.use_count() == 0, and use_count() is 0
after the default constructor or after reset(). It can also drop to zero
after the last shared_ptr is destroyed.

> What I am trying to do is have a "current" pointer that takes the
> value
> of something I want to be set (or note the fact that nothing is set),
> but I don't care if the object dies while that pointer is set -- in
> fact
> I don't want to keep it alive because I don't have an easy way to call
> reset on current were I to make it a shared_ptr.

But why do you need to compare weak_ptrs for that?


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net