A destructor is a class routine that cleans up an object once a program finishes using that object. As for constructors, HLA does not provide a special syntax for creating destructors, nor does HLA automatically call a destructor. Unlike constructors, a destructor is usually a method rather than a procedure (because virtual destructors make a lot of sense, whereas virtual constructors do not).
A typical destructor might close any files opened by the object, free the memory allocated during the use of the object, and, finally, free the object itself if it was created dynamically. The destructor also handles any other cleanup chores the object may require before it ceases to exist.
By convention, most HLA programmers name their destructors destroy
. About the only code that most destructors have in common is the code to free the storage associated with the object. The following destructor demonstrates how to do this:
procedure tBase.destroy; @nodisplay; begin destroy; push( eax ); // isInHeap uses this. // Place any other cleanup code here. // The code to free dynamic objects should always appear last // in the destructor. /*************/ // The following code assumes that esi still contains the address // of the object. if( mem.isInHeap( esi )) then free( esi); endif; pop( eax ); end destroy;
The HLA Standard Library routine mem.isInHeap
returns true if its parameter is an address that mem.alloc
returned. Therefore, this code automatically frees the storage associated with the object if the program originally allocated storage for the object by calling mem.alloc
. Obviously, on return from this method call, ESI will no longer point at a legal object in memory if you allocated it dynamically. Note that this code will not affect the value in ESI nor will it modify the object if the object wasn't one you've previously allocated via a call to mem.alloc
.