C++ - overload operator new and provide additional arguments

五迷三道 提交于 2019-12-05 23:52:48

问题


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.



来源:https://stackoverflow.com/questions/8685469/c-overload-operator-new-and-provide-additional-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!