Delete operator - how to implement?

Under normal conditions, I know how to take care of memory reallocation. My case is a little different.

I implement my own memory pool. I want the client of my class to be as close as possible to the general allocation and allocation method.

inline void* operator new(size_t dead_param, CPool& objPool) { return objPool.Allocate(); } 

I have this global function, so a user of my class can just call

Base baseObj = new (poolObj)Base2();

Now I do not know what to call the destructor? I have no NO IDEA

although I have a global delete operator

 inline void operator delete(void* ptr, CPool& objPool) { objPool.DeAllocate(ptr); } 

please direct .. how can I call this function from client code? With minimal syntax changes by the user. Also note that I don't want users of my code to implement operator new and operator delete and call Allocate and DeAllocate from there.

+5
source share
1 answer

In short: with a new placement, this is the only case where an explicit call to the destructor is in order:

baseObj-> ~ Base ();

But that seems awkward, because using your memory pool, you actually force the end user to execute all the books ... this makes your memory pool class no better (and maybe a little worse) than just using std :: vector .

I would not have the user of the newest placement ... rather, if you supply your own memory pool, this should be done with 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 more utility, and the end user just creates his own std::vector<uint8_t> .

It should be noted that this does nothing to make T not allocate anything else on the heap ...

+1
source

Source: https://habr.com/ru/post/1208674/


All Articles