|
Boost Users : |
Subject: Re: [Boost-users] Object pools?
From: Ryan McConnehey (mccorywork_at_[hidden])
Date: 2010-02-18 11:27:03
Igore Dmit. wrote:
> As far as I understand, you need to maintain a malloc'ed "your own"
> heap with some pool, but need to keep the heap alive if some objects
> are still in use but the pool is destroyed. boost::shared_ptr
> constructor that accepts deleter can be useful I guess. Sorry for
> abusing with bad formatted code:
>
> class PoolObjectDeleter {
> shared_ptr<void> pool_mem;
> weak_ptr<Pool> pool;
> PoolObjectDeleter(shared_ptr<Pool> & p, shared_ptr<void> & mem)
> : pool(p), pool_mem(mem) {}
> // provide copy constructor if customization needed
> void operator()(T* p) {
> // placement delete could go here
> shared_ptr<Pool> sp_pool = pool.lock();
> if(sp_pool)
> sp_pool->deallocate(p);
> }
> }
>
> class Pool : enable_shared_from_this<Pool> {
> // ...implementation details...
> shared_ptr<void> pool_mem;
> shared_ptr<T> allocate() {
> T *obj;
> // ... find usable object... use palcement new if needed I guess
> PoolObjectDeleter d(shared_from_this(), this->pool_mem);
> shared_ptr<T> ret_value(obj, d);
> return ret_value;
> }
> void deallocate(T *p) { /* implementation */ }
> }
>
> Pool holds shared_ptr to memory, so if pool is destroyed and no
> objects are allocated / in use, memory released. It looks that one had
> to provide class to wrap malloc'ed memory malloc/free so that
> new/delete would work. When object is created, copy of deleter holds
> shared_ptr to memory protecting it from destruction, and weak_ptr to
> pool allowing user to destroy it. When pool is destroyed and some
> objects are still shared_pointed by user deleter could not deallocate
> it with pool, but still placement delete the object and reduce
> refcounter on memory, destroying it with last used object removal.
I like your concept for deallocating the object that pool handed out. I
am using a private static class within pool to provide the function to
the shared_ptr destructor. This allowed the object to be delete if the
pool was destroyed but causes a bottleneck for other pools of the same type.
I have two questions. One, shouldn't the PoolObjectDeleter should be a
template class? Two, why is the PoolObjectDeleter passed a
shared_ptr<void>? It seems the pool_mem is to help with reference
counting to determine if the pool is destroyed. Yet, I thought the
enable_shared_from_this took care of the reference counting with the
pool.lock().
Ryan
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