C ++ - the overload operator new and provides additional arguments

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

for example

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

Since I want to override the new operator as follows

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

thanks

EDIT: Here I want to execute:

I have a piece of virtual memory allocated at the beginning of the application (memory pool). All objects that inherit my base class inherit its overloaded new operator. The reason I sometimes want to pass an argument to overloaded new is to tell the memory manager whether I want to use the memory pool, or if I want to allocate it using malloc.

+7
source share
1 answer

Invoke a new one with this additional operand, for example

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

additions

A practical example of passing the argument [s] to your new operator is given the Boehm garbage collector , which allows you to encode

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

and you don’t need to worry about delete -ing acollectedmonkey (assuming its destructor doesn’t do strange things, see this answer ), These are rare situations when you want to pass an explicit Allocator argument to a template collection, for example std::vector or std::map .

When using memory pools, it is often required to have a MemoryPool class and pass instances (or pointers to them) of this class to your new and your delete operations . For reasons of readability, I do not recommend referring to memory pools by any obscure integer.

+13
source

All Articles