C ++-重载运算符new并提供其他参数 [英] C++ - overload operator new and provide additional arguments

查看:166
本文介绍了C ++-重载运算符new并提供其他参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以使运算符new重载.当您这样做时,默认情况下会向您的方法发送一个size_t参数.但是,是否可以将size_t参数以及其他用户提供的参数发送到重载的new运算符方法?

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?

例如

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)
{

...

}

谢谢

我在应用程序(内存池)的开头分配了一块虚拟内存.继承我的基类的所有对象都将继承其重载的new运算符. 我有时要在重载new中传递参数的原因是告诉我的内存管理器是否要使用内存池,或者是否要使用malloc分配它.

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.

推荐答案

使用该附加操作数(例如

Invoke new with that additional operand, e.g.

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

附录

new运算符的实际示例. > Boehm的垃圾收集器,可让您进行编码

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);

,然后您就不必为delete -ing acollectedmonkey操心(假设其析构函数没有做任何奇怪的事情;请参阅

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.

使用内存池时,您通常希望拥有一些MemoryPool类,并将该类的实例(或指向它们的指针)传递给您的new delete 操作.出于可读性原因,我不建议使用一些晦涩的整数来引用内存池.

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.

这篇关于C ++-重载运算符new并提供其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆