Okay, I'm a little confused. I'm just playing around with malloc and placement new, and I'm struggling a little bit with how a class is allocated.
foo* mem_pool = (foo*) malloc(sizeof(foo)*3);
After defining a memory pool with room for 3 foo objects, I attempted to create a class in the pool with placement new. If it is the first one written to the pool (any arbitrary location, though I am using the beginning here), I can dereference it correctly. Cool.
1 2 3
foo* sPtr1 = new (mem_pool) foo(3.1, 4.1); //create foo object at beginning of pool
mem_pool->x; //returns 3.1
mem_pool->y; //return 4.1
After that, I attempt to write a second class at mem_pool+sizeof(foo). The dereference returns junk data...
Your pointer arithmetic is wrong. To allocate the second object you use mem_pool + 1, not mem_pool + sizeof(foo). If your mem_pool pointer were of type char or unsigned char, then yes, it would be as you have it.
Interesting you're are trying to manage classes using memory pools. So in theory you could deconstruct a group of classes just using one free command. I don't think using new or delete for this purpose would work since they are probably used for single class allocation and not multiple.
Thank you very much webJose, that is exactly what I was getting wrong. I went ahead and read up on pointer arithmetic so I could get a better understanding of how they worked. ;)
@ceruleus Actually, I overlooked that I was using delete instead of free at the very end. That's my bad. :P I wanted to experiment with void* pools for flexibility, and using new requires that I use objects.
@cppabuser/andywestken I wasn't planning on using delete to manage the objects inside the pools. I wanted to try out overloading new/delete so it would simply mark 'deleted' objects as available. Then at the end of the program, all I would do is free the pools for garbage collection.
Anyways, I had another question. I decided to go the route for using char* for pointer arithmetic. However, what would I do if the compiler's sizeof(char) is not equal to 1? Is there a way I can explicity define that, or a 1 byte pointer?