I am currently 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 only 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'm going to provide my group of projects with allocators like this, and I want them to actually use them, instead of refusing to call new
, since we need these faster allocators to manage our memory.
But for this I will have to develop the simplest possible syntax for initializing a variable using my custom allocators.
My decision
It was best to override operator new
in each class, as it is a distribution 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 for initializing the variable becomes what I ultimately want:
MyClass *obj = new(alloc) MyClass(3.14);
However, it would be great if I had a common equivalent of the above. Therefore, I would not have to redefine operator new
for each class.
source share