NEW's actual form

xiaoxiao2021-03-06  111

If we overload a new operation symbol, then the orthodox overload mode is:

Void * Operator new (unsigned int usize) (1)

{

Return Malloc (usize);

}

Maybe you have discovered, sometimes, New's form is much more complicated, such as the NEW under the MFC (in Debug Edition) is like this:

Void * Operator New (unsigned int usize, const char * szfilename, int nline) (2)

{

...

}

Of course, it is defined in this way, doesn't use New:

INT * p = new int [4];

So, I use this form, how did it call (2)?

Smart you may have discovered, found such a macro in your file:

#ifdef _Debug

#define new debug_new

#undef this_file

Static char this_file [] = __file__;

#ENDIF

Hoho, didn't you see? Your New is replaced with Debug_New. (Strange? How can I be in the stuff in Define? Don't be strange, you can even #define while for, how do you see your program? If you do it, then give someone to see, try Test effect :)

Continue to track, see Debug_new definition:

#define debug_new new (this_file, __LINE__)

Then we restore it into our original usage method, it is actually like this:

INT * p = new (__ file__, __line__) int [4];

Finally, it will become in the Operator new function:

INT * P = Operator New (SIZEOF (INT) * 4, __File__, __Line__);

Strange, huh, it is like this;

That is, you can override a new New, as long as the first parameter is about the type of size, then the back parameters can be given casually; so the MFC uses this, and the NEW is overloaded to (2) In this way, they can get the file names that each new call and the number of rows in the source file, and then record it, so when Delete can check all the original application, as long as there is a memory that is released The pointer (that is, the memory leaks) will give a tip, and tell you which new (which source file is located in which the source file is not released.

Note: According to ANSI C, __ file__ represents the file name of the current source file, __ line__ represents the number of rows located at the current source file. Visual C follows this provision and has an expansion, see MSDN.

转载请注明原文地址:https://www.9cbs.com/read-101104.html

New Post(0)