Boost logo

Boost :

From: Joe Gottman (jgottman_at_[hidden])
Date: 2005-08-03 19:16:06

"Andy Thomas-Cramer" <Andy_Thomas-Cramer_at_[hidden]> wrote in message
> I have a weak_ptr that might be empty. If not empty, I'd like to make a
> smart pointer from it.
> But the code below throws in the shared_ptr constructor, and I don't see
> how to test whether a weak_ptr is empty.
> boost::weak_ptr<int> wp;
> boost::shared_ptr<int> sp(wp);
> if ( sp.get() ) {
> ...
> }
> Suggestions?

It depends what you mean by empty. A weak_ptr can either
    a) be associated with a valid shared_ptr
    b) be associated with a shared_ptr that has since expired
or c) be default initialized and never associated with a shared_ptr

If you don't need to differentiate between case b) and c), the most elegant
way is
if (shared_ptr<int> sp = wp.lock()) {
    //do work with valid shared_ptr

If you need to distinguish between b) and c) you can continue with
 } else {
    weak_ptr empty;
    if (!(wp < empty) && !(empty < wp)) {
        //case c, default-constructed weak_ptr
    } else {
        //case b, expired weak_ptr

In practice, most people don't need to distinguish between case b) and c)

Joe Gottman

Boost list run by bdawes at, gregod at, cpdaniel at, john at