The delete Operator

The delete operator is overloaded to accept pointers that are near, far, huge, or based. When you delete an object, the addressing mode of the pointer determines which delete operator is invoked. Thus, the following example invokes four different delete operators:

npN = new Node __near;

fpN = new Node __far;

hpN = new Node __huge;

bpN = new Node __based(segvar);

delete npN; // Invokes near delete

delete fpN; // Invokes far delete

delete hpN; // Invokes huge delete

delete bpN; // Invokes based delete

The addressing mode of the pointer does not necessarily indicate the address space of the object. For example,

Node __far *fpN;

fpN = new Node __near; // Type conversion: near to far

delete fpN; // Error: far delete invoked for near object

In this example, the compiler chooses the inappropriate delete operator for the pointer, which results in a run-time error. To prevent this problem, you must explicitly cast the pointer to the desired addressing mode:

delete (Node __near *)fpN;

You must always ensure that the delete operator invoked corresponds to the new operator used to allocate the object.

Just as with the new operator, you can write your own version of the delete operator to implement a customized memory-allocation scheme. If you want to implement different behavior for the different versions of the delete operator, you must use one of the following prototypes:

void operator delete( void __near *nptr );

void operator delete( void __far *fptr );

void operator delete( void __huge *hptr );

void operator delete( __segment segvar, void __based(void) *bptr );

You can also define class-specific versions of any of these forms of delete. When defining a class-specific version, you can specify an optional final argument of type size_t. If present, the argument is automatically set to the size of the object being deleted. You cannot define two versions of delete that are distinguished only by the size_t argument; that is, you cannot overload the delete operator for a given addressing mode within class scope. However, you can define versions of delete that have the same addressing mode but different scopes; that is, one with global scope and one with class scope.

All the default versions of delete have the __cdecl calling convention.