Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator delete - how to implement?

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.

like image 484
Adorn Avatar asked Nov 10 '22 22:11

Adorn


1 Answers

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...

like image 80
IdeaHat Avatar answered Nov 14 '22 23:11

IdeaHat