限制重载new和Delete [英] Putting restrictions in overloading new and delete

查看:85
本文介绍了限制重载new和Delete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对重载运算符new和delete施加一些限制? 我超载的新文件在另一个文件中链接到我的测试程序.

Is it possible to put some restrictions in overloading operators new and delete? My overloaded new is linked in a different file to my test program.

场景是:

if(condition is satisfied)
   call overloaded new
else
   call the actual new defined in new.h

推荐答案

有三种方法可以为操作员提供新的操作.

There are three ways to provide an operator new.

  • 替换新的四个非展示位置默认运算符中的一个或多个

  • replacing one or more of the four non placement default operators new,

为默认的运算符new提供重载(因此,带有附加参数,可以使用placement new语法调用这些参数),

providing overload to the default operator new (thus with an additional parameter, those may be called with the placement new syntax),

为操作员提供新的类成员,这些成员将仅为该类及其后代调用.

providing operator new class members, those will be called only for that class and their descendant.

在后两种情况下,可以使用以下语法来调用一个更广为人知的运算符:

In the latter two cases, it is possible to call one of the more well know operators new with the syntax:

ptr = ::operator new(sz);
ptr = ::operator new[](sz);
ptr = ::operator new(sz, std::nothrow);
ptr = ::operator new[](sz, std::nothrow);

但是,如果您已更换它们,则会致电您的替换产品. 您不能将默认的运算符称为已替换的新运算符(也许您可以通过玩实现特定的链接器技巧,但这不在该语言的范围之内.)

but if you have replaced them, your replacement will be called. You can't call the default operators new you have replaced (well perhaps you can by playing implementation specific linker tricks, but that's outside the scope of the language).

关于更换运算符new:

About the replacement of operator new:

  • 您应该将两个运算符new和对应的两个运算符delete一起替换(或使用意外指针轻松地调用其中一个delete运算符)
  • 您应该将两个运算符new []和对应的两个运算符delete []一起替换(相同原因)
  • 请注意新处理程序可能带来的影响,某些库将对此发挥作用.

这篇关于限制重载new和Delete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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