#32231 - Steve++ - Sun Dec 19, 2004 7:12 pm
I'm having some trouble with my object pooling code. It's not giving the expected results. Here's the code:
The output is:
That's weird because I didn't set anything to 4. Ideas anyone?
Code: |
#include <stdio.h>
class Poolable { private: unsigned poolHandle; protected: Poolable() {} friend class ObjectPool; }; class ObjectPool { Poolable* pool; Poolable** stack; int size; int tos; public: void reset() { for (int i=0; i<size; ++i) { stack[i] = pool+i; pool[i].poolHandle = i; } tos = size-1; } ObjectPool(Poolable* pool, Poolable** stack, int size) : pool(pool), stack(stack), size(size) { reset(); } Poolable* allocate() { return tos >= 0 ? stack[tos--] : NULL; } bool deallocate(Poolable* p) { if (tos < size-1) { stack[++tos] = pool+p->poolHandle; return true; } else { return false; } } }; class TestObject : public Poolable { int x; public: TestObject() : x(0) {} int getx() { return x; } void setx(int x) { this->x = x; } }; int main() { TestObject pool[10]; TestObject *stack[10]; ObjectPool p(pool, (Poolable**)stack, 10); TestObject* a = (TestObject*)p.allocate(); a->setx(1); TestObject* b = (TestObject*)p.allocate(); b->setx(2); TestObject* c = (TestObject*)p.allocate(); c->setx(3); printf("%d %d %d\n", a->getx(), b->getx(), c->getx()); // prediction: 1 2 3 p.deallocate(a); p.deallocate(c); p.deallocate(b); a = (TestObject*)p.allocate(); b = (TestObject*)p.allocate(); c = (TestObject*)p.allocate(); printf("%d %d %d\n", a->getx(), b->getx(), c->getx()); // prediction: 2 3 1 return 0; } |
The output is:
Code: |
1 2 3 4 3 3 |
That's weird because I didn't set anything to 4. Ideas anyone?