Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - overload operator new and provide additional arguments

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.

like image 955
KaiserJohaan Avatar asked Dec 31 '11 00:12

KaiserJohaan


1 Answers

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.

like image 155
Basile Starynkevitch Avatar answered Oct 28 '22 11:10

Basile Starynkevitch