|
Boost Users : |
Subject: Re: [Boost-users] Object pools?
From: Igore Dmit. (trueorca_at_[hidden])
Date: 2010-02-18 05:46:39
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.
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