Reputation: 319
I'm currently working on a little game, and I need somes class/struct to be allocated and deleted really often. I'm wondering it is a way to save deletion, maybe putting delete object in a container, and try to pick up in this container when i want to allocate an instance of the class.
I'm thinkin about overload of new and delete operator. But I have a little problem, if I overload the delete operator (to put the "deleted" object in the container), How delete it? Should I pass throught proper function to do that?
Upvotes: 0
Views: 68
Reputation: 2453
There are two ways you could go with that
1) A pool of objects. When you "allocate" you take an object from the pool and when you deallocate you return it back to the pool. This is not that transparent but the implementation is not that hard.
2) Create a custom allocator for your classes/structs. You preallocate the memory in a big buffer and when you need to allocate you take memory from there and when you need to deallocate you return the memory back (the actual mechanism is up to you). This is a bit harder to implement but can be more transparent.
Check the following links for ideas
Also, while you are at it, there is a great book by Alexandrescu
http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315
a bit old, but exceptional nevertheless and has a section for memory management/allocator.
Upvotes: 4
Reputation: 17444
Make a class using this simple interface:
class allocator
{
object* get();
void release(object*);
};
Now, the decision when an object is actually destroyed and when it is stored for later reuse is made by that container. This also makes clear where the objects come from, i.e. that they are managed by this allocator.
Upvotes: 0
Reputation: 588
You can always make a free list for your objects. Then when you want to delete an object, add it to the free list instead. If you know you won't ever be using that object again, free the memory and don't add it to the list.
Maybe if you tell us more about the logic behind your allocation/deallocation we can help you find a better way as well. Like what objects are you allocating? Is it for the same thing just with different values?
Upvotes: 0