Currently I am working on custom memory allocation and one of the drawbacks is that I have to write multiple lines to achieve the same result that the new-expression provides with just one simple call.
Simple initialization:
MyClass *obj = new MyClass(3.14);
Less simple initialization:
void *obj_mem = alloc->Allocate(sizeof MyClass, alignof(MyClass));
MyClass *obj = new(obj_mem) MyClass(3.14);
I am going to provide my project group with allocators such as that one, and want them to actually use them, instead of falling back on calling new
, since we'll need these faster allocators to manage our memory.
But for that to happen, I will have to devise the simplest possible syntax to initialize a variable with my custom allocators.
My Solution
My best bet was overriding operator new
in each class, since it is the allocation function for the new-expression.
class MyClass
{
...
void* operator new(size_t size, Allocator *alloc)
{
return alloc->Allocate(size, alignof(MyClass));
}
}
And then the syntax to initialize a variable becomes what I ultimately want:
MyClass *obj = new(alloc) MyClass(3.14);
However, it would be great if I could have a general equivalent of the above. So I wouldn't have to override operator new
for each class.