If we need to reload a new operator symbol, the Orthodox reload method is:
Void * operator new (unsigned int usize)(1)
{
Return malloc (usize );
}
You may have discovered that sometimes the form of new is far more complex than this. For example, the form of new in MFC (in the debug version) is as follows:
Void * operator new (unsigned int usize, const char * szfilename, int nline)(2)
{
...
}
Of course, such a definition will not allow you to use new in this way:
Int * P = new int [4];
So, how can I call this form?(2)?
You may have discovered this clever macro in your file:
# Ifdef _ debug
# Define new debug_new
# UNDEF this_file
Static char this_file [] = _ file __;
# Endif
Hoho, see? Your new is replaced with debug_new. (Strange? How can keywords be defined by define? Don't be surprised. You can even # define while for to see what will happen to your program? If you do this, show it to others and try the effect :)
Continue to trace and see the definition of debug_new:
# Define debug_new new (this_file, _ line __)
Then we restore it to our original usage, which is actually like this:
Int * P = new (_ file __, _ line _) int [4];
Finally, it becomes in the operator new function:
Int * P = Operator new (sizeof (INT) * 4, _ file __, _ line __);
That's strange;
That is to say, you can reload and write a new one by yourself. As long as the first parameter is about the type size, the following parameters can be given at will; so MFC uses this, reload new(2)In this way, they can get the file name of each new call and the number of lines in the source file, and then record all the records, so that when the delete operation can check all the originally applied memory, as long as there are no released memory pointers (that is, the memory leaks), a prompt will be displayed, and you will be notified of which new (which line of the source file it is located in) the Applied memory is not released.
Note: According to ansi c, __file _ indicates the file name of the current source file, and __line _ indicates the number of lines in the current source file. Visual c ++ follows this rule and has been expanded. For details, see msdn.