I have a function that calls a lot of object constructors, which in return these constructors will allocate a lot of memory.
Now, in my program I am sure that if I first call this function , say it will call the constructor of 100 object.
If I call this function again and again, I am sure that it will only call the constructor 100 times again, and thus I am sure that the memory allocated in the first call can be reused again.
How can I reuse the memory allocated in the first call?
Can I use something like boost:object_pool so that I can tell the pool to restart from the begining and do not allocate extra memory, just use what you already have?
You have to create a class that manages these "allocated memory pool" so that whenever you want to allocate new memory, you tell this class to allocate you a memory.
So, if a memory has already been allocated but isn't being used, then this class will return the address to that memory.
Of course, this class will have to keep track of the allocated memory that isn't used.
1 2 3 4 5
class memory
{
...
}
int *ptr=memory.getMemory(size)
Either that, or you just delete all the memory that you allocated for your class in your deconstructor
1 2 3 4 5 6 7 8 9 10 11 12 13
class something
{
int *pointer;
public:
something(); //This is a constructor
{
int *pointer=newint[10];
}
~something(); //This is a deconstructor
{
delete [] pointer;
}
};
I just do not want to keep calling new/delete every time. Because I am sure that if I call the main function again and again it will need the exact same size of the memory every time.
Is there any thing in the std:: or the boost:: libraries that does your first suggested option?
boost:object_pool<> does not throw std::bad_alloc on failure; it is not a singleton pool, so we have to manage the pool lifetime explicitly; and it is not a standard library compatible allocator.
boost::pool_allocator<> and boost::fast_pool_allocator<> are singleton pools with exceptions and are written as standard library compatible allocators. Though you would find that they are a wee bit more expensive, their usage is far more convenient.
Thank you JLBorges
I just have couple of questions:
1) Why do we need the A::vector and A::map? are they required in the memory allocation algorithm or just some data.
2) You said that there is a total of 100k objects allocated. Which means that every time foo() is called another 10000 object are allocated.
What I want is at the first time the foo() is allocated, only 10000 is allocated. Then the next time foo() is called we reuse the memory. It is like moving the pointer of the pool back to the beginning and re using the memory.