14.11 Destructors


14.11 Destructors

A destructor is a class routine that cleans up an object once a program finishes using that object. Like 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 while virtual constructors do not).

A typical destructor will 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. Destructors generally do not have any parameters, so the issue of overloading the parameter list rarely arises. 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( isInHeap( esi )) then           free( esi );      endif;      pop( eax ); end Destroy; 

The HLA Standard Library routine isInHeap returns true if its parameter is an address that malloc returned. Therefore, this code automatically frees the storage associated with the object if the program originally allocated storage for the object by calling malloc. 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 malloc.




The Art of Assembly Language
The Art of Assembly Language
ISBN: 1593272073
EAN: 2147483647
Year: 2005
Pages: 246
Authors: Randall Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net