I know in normal circumstances how to take care of memory de-allocation. My case is little different.
I am implementing my own memory pool. I would want client of my class to be as near to general method of allocation and de-allocation.
inline void* operator new(size_t dead_param, CPool& objPool)
{
return objPool.Allocate();
}
i have this global function, so that user of my class can simply call
Base baseObj = new (poolObj)Base2();
Now I don't know how to call destructor? I clearl have NO IDEA
though I have global operator delete
inline void operator delete(void* ptr, CPool& objPool)
{
objPool.DeAllocate(ptr);
}
please guide.. how can i get this function called from client code? With minimal changes to syntax from user side. Also note I do not want users of my code to implement operator new
and operator delete
and call Allocate
and DeAllocate
from there.
The short of it: With placement new is the only case where explicitly calling the destructor is OK:
baseObj->~Base();
But this seems wonky because, with your memory pool, you're actually making the end user do all the book keeping...this makes your memory pool class no better (and arguably a little worse) than just using a std::vector.
I would not have the user do the placement new themselves...rather, if supplying your own memory pool, it should be done withing the ObjectPool class:
class ObjectPool {
public:
template <typename T, typename... A>/*c++ 11 ftw*/
T* allocate(A... args) {
void* create_location;//pool figures out where this is, probably with sizeof<T>
return new (create_location) T(args...);
}
template <typename T>
void dellocate(T* t) {
t.~T();//With placement new, this is the one place this is OK
//pool marks that memory as avaiable to be allocated in
}
}
Honestly, this is the only way for your pool to have any more utility then the end user just making their own std::vector<uint8_t>
.
It should be noted that this does nothing to keep T from allocating anything else on the heap...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With