C++ - overload operator new and provide additional

2019-04-07 01:51发布

问题:

I know you can overload the operator new. When you do, you method gets sent a size_t parameter by default. However, is it possible to send the size_t parameter - as well as additional user-provided parameters, to the overloaded new operator method?

For example

int a = 5;
Monkey* monk = new Monkey(a);

Because I want to override new operator like this

void* Monkey::operator new(size_t size, int a)
{

...

}

Thanks

EDIT: Here's what I a want to accomplish:

I have a chunk of virtual memory allocated at the start of the app (a memory pool). All objects that inherit my base class will inherit its overloaded new operator. The reason I want to sometimes pass an argument in overloaded new is to tell my memory manager if I want to use the memory pool, or if I want to allocate it with malloc.

回答1:

Invoke new with that additional operand, e.g.

 Monkey *amonkey = new (1275) Monkey(a);

addenda

A practical example of passing argument[s] to your new operator is given by Boehm's garbage collector, which enables you to code

 Monkey *acollectedmonkey = new(UseGc) Monkey(a);

and then you don't have to bother about delete-ing acollectedmonkey (assuming its destructor don't do weird things; see this answer). These are the rare situations where you want to pass an explicit Allocator argument to template collections like std::vector or std::map.

When using memory pools, you often want to have some MemoryPool class, and pass instances (or pointers to them) of that class to your new and your delete operations. For readability reasons, I won't recommend referencing memory pools by some obscure integer number.