Re: how to use a pool
"abir" <abirbasak@gmail.com> wrote in message
news:c27f1871-98b9-497f-b74d-acfe4b2a7115@d36g2000prf.googlegroups.com...
I am interested to allocate and deallocate lots of objects of same
type (and of course size). As the deallocation will take place in
random order and also the maximum number of objects at any time is not
known (though i have a hint), i can't use a vector for this purpose.
Thus i developed a memory pool for fixed objects(an allocator).
i can make the pool as a template of object type or object size.
at present what i am doing is,
1)
template<size_t sz>struct mypool;
struct myobj;
mypool<sizeof(myobj)> pool(1024);///1024 -> typical pool size
void* ptr = pool.allocate();
myobj* obj = new(ptr)(x,y,z);////where x,y,z are myobj constructor
params.
similarly te destruction is done as,
obj->~myobj();
pool.deallocate(obj);
if i want to have a single step solution for them like
2)
template<typename T> struct mypool;
myobj* ptr = pool.create(x,y,z);
pool.drop(ptr);
Here he first step (ie create ) i can't write as i can't forward the
x,y,z to the class constructor.
I have to use a copy constructor like,
myobj* ptr = pool.create(myobj(x,y,z));
any myobj doesn't have one!.
[...]
You can indeed forward multiple arguments to class ctor. Look here for more
info:
http://groups.google.com/group/comp.lang.c++/browse_frm/thread/419bf7caebf53ac
Caveat, you have a problem with passing references. Template arguments seem
to deduce down to copy semantics instead of passing by reference. This can
be solved with a macro:
<pseudo-code!!!!>
template<typename T>
class allocator {
// [impl detail];
public:
void* allocate() {
void* mem = // impl detail;
return mem;
}
void deallocate(T* mem) {
mem->~T();
// impl detail
}
};
#define YOUR_NEW(a) new ((a)->allocate())
struct foo {
int a;
foo(int a_) : a(a_) {}
};
void foobar() {
allocator<foo> foo_alloc;
foo* f1 = YOUR_NEW(&foo_alloc) foo(1);
foo* f2 = YOUR_NEW(&foo_alloc) foo(2);
foo* f3 = YOUR_NEW(&foo_alloc) foo(3);
foo_alloc.deallocate(f3);
foo_alloc.deallocate(f2);
foo_alloc.deallocate(f1);
}
Problem, exceptions in ctor... How would you solve?
;^D