質問

I am trying to simplify a library by adding a macro. I have been reading about all the different things that macros can accomplish, but have had no luck implementing something that works the way I intend.

I wrote a memory manager that is to be used with the placement new feature. It keeps track of what is allocated and where it is in the preallocated space.

Ideally, I would like to write something like:

MyClass* c = New(mem) MyClass(3); // use memory manager instance 'mem' and constructor 'MyClass(int)'

and have it translate to:

MyClass* c = new (mem.Reserve<MyClass>()) MyClass(3);

for single allocations, and:

MyClass* c = New(mem) MyClass[33]; //use memory manager instance 'mem' and default constructor to initialize and array of 33 MyClass objects

translate to:

MyClass* c = new (mem.Reserve<MyClass>(33)) MyClass[33];

The Reserve< TYPE >(SIZE) method is what manages the internal parameters. It reserves (sizeof(TYPE)*(SIZE)) bytes in the preallocated memory managed by mem and returns the pointer of the starting address to the placement new function.

Is this a feasible operation for a macro? Or is there a better way to approach this?

I am limited to C++03 standard as that is what my ARM compiler supports.

I appreciate any advice and examples to help me understand this better! Thanks!

役に立ちましたか?

解決

Following may help:

#define New(mem, Type) new (mem.Reserve<Type>()) Type
#define NewArray(mem, Type, Size) new (mem.Reserve<Type>(Size)) Type[Size]

Use it like:

MyClass* c = New(mem, MyClass)(3);       // new (mem.Reserve<MyClass>()) MyClass(3);
MyClass* c = NewArray(mem, MyClass, 33); // new (mem.Reserve<MyClass>(33)) MyClass[33];

Maybe defining void* operator new(size_t n, MemoryManager& mem); may help also (if Reserve<MyClass> use MyClass only to know its size).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top