class overloaded new and delete vs placement new with a bespoke memory class

我怕爱的太早我们不能终老 提交于 2019-12-25 00:27:19

问题


I am investigating the pros and cons between using class overloaded news and deletes vs placement news. By this I mean, either declaring every class I may wish to new and delete with their own operator overloads, or by using the memory manager to give me the memory I need via placement new.

I have a memory manager that allows me to allocate memory from a number of pools:

enum MemPool
{
  kPool1,
  kPool2,
}

class MemoryManager
{
public:
  template <typename T>
  void* Allocate(MemPool pool); 
  void  Remove(MemPool pool, void* ptr);

};

MemoryManager g_mmgr;

The Allocate is templated since in debug mode I store the name of each allocation (via typeid(T).name()) and I can get the size of each allocation via sizeof(T)

I see myself as having at least 2 options as to how to allocate and am trying to decide which is best in terms of syntactical usage, efficiency, safety and portability.

Option 1 is to have a templated base class with news and deletes, which wraps up the mempool and type nicely for me.

template <typename T, MemPool pool>
class MemPoolUser
{
public:
  static void* operator new(int size)
  {
    return g_mmgr.Allocate<T>(pool);
  }

  static void operator delete(void* ptr)
  {
    g_mmgr.Remove(pool,ptr);
  }
};

I could then ensure that every class that may need newing via the MemoryManager is declared thus:

class MyClass : public MemPoolUser<MyClass, kPool1>
{

};

This will allow me to simply do

MyClass* c = new MyClass();
...
delete c;

and the correct new and delete inside MemPoolUser will be called.

Option 2 is to use placement news:

class MyClass
{

};

MyClass* c = new (g_mmgr.Allocate<MyClass>(kPool1)) MyClass();
....
c->~MyClass();
g_mmgr.Remove(kPool1,c);

Any pros and cons to each of these options? Option 1 seems neater, but I have to know the type of mempool I want each class to allocate from, which may depend on other runtime factors.

Option 2 is more flexible but the newing and deleting is syntactically ugly (it could be wrapped in #defines)

So my question is, apart from the above problems mentioned, is there anything else I have failed to consider with these two options and is one more hazardous than the other?


回答1:


If you MUST do this in the first place (and I expect you do have some pretty decent use-case where which has some specific need for a specific memory pool for these object), I would definitely go for the operator new and operator delete solution. It allows your application-code that uses this to be written with a minimal amount of extra coding above and beyond the typical code.



来源:https://stackoverflow.com/questions/16193846/class-overloaded-new-and-delete-vs-placement-new-with-a-bespoke-memory-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!