开发者

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?

The legacy code that I am developing with has a requirement that there is no dynamic memory allocation after the bootstrap has completed. 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.

Is there a way of overloading global new and then calling it?开发者_如何学运维


No, you can't "overload" global new - only replace it. 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.


Not Overloading but Replacing new globally is indeed possible.

The C++ standard has set of predefined new and delete operators. 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.

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.


you can probably try:

#define new new(your imagination)

and later undefine it depends on your situation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜