[英]How could I prohibit use of “new” in certain parts of C++ code?
Is it possible to prevent new from being used at certain points in the code?是否可以防止在代码中的某些点使用 new ?
The legacy code that I am developing with has a requirement that there is no dynamic memory allocation after the bootstrap has completed.我正在开发的遗留代码要求在引导完成后没有动态 memory 分配。 We now want to test this.我们现在要对此进行测试。
If I was starting the development from scratch then I could write my own wrapper and use that, or overload operator new in a common base class.如果我从头开始开发,那么我可以编写自己的包装器并使用它,或者在公共基础 class 中重载 operator new。
Is there a way of overloading global new and then calling it?有没有办法重载 global new 然后调用它?
No, you can't "overload" global new
- only replace it .不,您不能“重载”全局new
-只能替换它。 However in your replacement you can check for a global flag meaning "new allowed" (and throw an exception if that flag is not set) and change that flag from inside calling code.但是,在您的替换中,您可以检查表示“允许新”的全局标志(如果未设置该标志,则抛出异常)并从调用代码内部更改该标志。 This won't help against overloaded operator new
in classes unless you change each overload to also respect that flag.除非您更改每个重载以也尊重该标志,否则这对防止类中的重载operator new
没有帮助。
Not Overloading but Replacing new globally is indeed possible.不重载而是全局替换新的确实是可能的。
The C++ standard has set of predefined new and delete operators. C++ 标准具有一组预定义的新建和删除运算符。 The most commonly used versions are:最常用的版本是:
void* operator new(std::size_t) throw(std::bad_alloc);
void operator delete(void*) throw();
void* operator new[](std::size_t) throw(std::bad_alloc);
void operator delete[](void*) throw();
The first two versions allocate & deallocate memory for an object, the last two are for array of objects.前两个版本为 object 分配和释放 memory,后两个版本用于对象数组。
If you provide own versions of these is called replacing the ones from the standard library.如果您提供自己的版本,则称为替换标准库中的版本。
If you overload operator new
, you should always also overload the matching operator delete
, even if will be never called or used by you.如果你重载 operator new
,你应该总是重载匹配的 operator delete
,即使你永远不会调用或使用它。
you can probably try:您可能可以尝试:
#define new new(your imagination)
and later undefine it depends on your situation然后取消定义它取决于你的情况
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.