I’m making a small game engine and need to have a memory pool associated with it.
My question is, how do I actually share that memory to users who got their own classes?
For example, I have a user who got this class in his game;
class Monkey : public GameObject {
public:
Monkey();
~Monkey();
void Eat();
void Sleep();
unsigned long size();
private:
int health;
};
I got a baseclass which, at the moment, just returns the size of the derived class. I figured this would be needed to know how much space this would occupy in the pool.
public GameObject {
public:
virtual unsigned long size()=0;
};
And he wants to allocate a new instance of this class in my memory pool.
I do not know the class definition at compile time,so I just can’t figure out how the actual method call would look like. He cannot pass me an object inheriting from GameObject, because that means he already has allocated it, which defeats the purpose of pre-allocated memory pool. So how does the reserving of memory actually work for any arbitary class instance?
Sorry if its unclear
Memory pools only allow allocations of a fixed size. Therefore, if you’re trying to allocate variable size objects with one, then the fixed size of the allocation is the maximum size you can allocate.
If you want to overload the allocation behavior, you need to overload
operator new/deleteon your base class. It shouldthrow std::bad_allocif the user attempts to allocate a type beyond the max size of the memory pool. Also, you should overloadoperator new[]/delete[]to justthrow std::bad_alloc, since allocating arrays of these will probably not be a good idea.The overloaded
operator new/deletewill be given the proper size of the type it is allocating. All derived classes will inherit the overloaded operators… unless the user overrides it. And if they do… smack them.The overloading itself is simple:
You will implement those by calling your pool to fetch a block of memory, or to deallocate the block of memory.