Overload of New and Delete operators in VC

xiaoxiao2021-03-19  214

Reserving the New and Delete operators in C can bring more flexible storage control to the program, which is essential for applications such as game design. The general C books will also introduce their applications and implementations, however there are several places that must be noted in the VC, otherwise the compile will have problems.

Implementation

First, the VC adds the following code in each automatically generated CPP file:

#ifdef _debug # undef this_filestatic char this_file [] = __ file __; # Define new debug_new # Endif

As can be seen from the red font above, the New NEW is defined in debug mode to debug_new, so the code that implements the new function should be placed before this definition, otherwise the compile will report an error.

So what is debug_new? You can find the answer in the AFX.H file:

#define debug_new new (this_file, __LINE__)

Thus, in Debug mode If we call as follows:

CWND * PWND = New CWND;

Becomes

CWND * pwnd = new (this_file, __line__) CWnd;

The above code is equivalent to calling New (SizeOf (CWnd), this_file, __LINE__) function, and its prototype is:

Void * Operator New (size_t, lpctstr, int);

So our New operator must be defined as the above in Debug mode.

2. Several questions

2.1 Delete matching problem

If you implement the void * operator new (size_t, lpctstr, int) operator, it is best to achieve corresponding to it.

Void Operator Delete (Void * P, LPCTSTR, INT)

Operator, otherwise the compiler will report a warning error: no matching operator delete Found; Memory Will Not Be Fre IF Initialization Throws an Exception.

2.2 Members new operator overload

If you overrupt the NEW and DELETE operators of the class, they must declare them as static members. This is because the compiler adds a THIS parameter to the end of the end; in addition, the class has not been constructed when calling New. The above has led to the requirements for static statements.

2.3 Global New Operation Operator

If you want to overload the global new and delete operators, just implement the following functions (RELESE mode):

Inline void * __cdecl operator new (size_t size); inline void __cdecl operator delete (void * p);

No statement is required, as long as the above functions are implemented in some place, all new operations call our functions. But in Release mode, there is a problem: New and delete are inconsistent. In a test program I implemented (VC6.0, the multi-document program that is default automatically), New is called 5 times, while Delete is only called 3 times, and the new operation that is called two times does not correspond. DELETE operation. I don't know if I call other delete prototypes.

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

New Post(0)