Boost logo

Boost :

Subject: Re: [boost] Weak pointer to object not managed by a shared_ptr
From: Stefan Strasser (strasser_at_[hidden])
Date: 2009-09-02 15:12:46


Am Wednesday 02 September 2009 18:55:03 schrieb Ryan Gallagher:
> For using this, think about X lifetimes being managed by some other
> class (XManager). Think about another class A that isn't managed
> my XManager but needs to weakly reference some X instance.
>
> Perhaps someone else can give a better, more realistic, example
> though, as even this one I wouldn't code this way.

I actually use that technique (without knowing the linked document).
but I can't think of very many other use cases:

My case handles a lot of objects that are not required to stay in memory but
are also not supposed to be destroyed immediatly after they've been used, so
they're not constantly re-created if they're used more than once (loaded back
from disk in my case).

class cache_element : public intrusive::slist_base_hook<>{
...
private:
        shared_ptr<cache_element> this_;
...
};

class object : cache_element{
...
};

the objects are only referenced by weak_ptr's throughout the code, and loaded
back from disk if weak_ptr::lock() fails.
so the only reference keeping the object in memory is an object cache, which
fills cache_element::this_ on first access and removes the element from the
list of cached elements when the cache overflows, using a disposer like that:

struct disposer{
        void operator()(cache_element *element){
                shared_ptr<cache_element> ptr;
                ptr.swap(element->this_);
        }
};


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk