Release method?
BlitzMax Forums/BlitzMax Programming/Release method?
| ||
Is there any way to create a "Release" function for a type so that when the variable is set to Null, your release function is called? Like let's say I have an OpenGL viewport structure. Can I set up a function that will automatically be called when an instance is deleted, so that I can delete OpenGL objects automatically? |
| ||
Type tthing Method New() Print "Created" EndMethod Method Delete() Print "Deleted" EndMethod End Type Local t:tthing = New tthing t=Null GCCollect() |
| ||
this doesnt always work in my experiance, the delete method sometimes will not be called for some odd reason |
| ||
Then how else do you delete something? |
| ||
I typically have a base class for everything.Type IDisposeable Field __disposed%=0 Method Dispose( ) If __disposed Then Return __disposed = 1 End Method Method Delete( ) Dispose( ) End Method End Type Type TBlah Extends IDisposeable Method Dispose( ) ' Do some stuff specific to this type ' Call the method in the base class so ' stuff specific to it gets done too Super.Dispose( ) End Method End Type |
| ||
Delete() will only fire when all references to an object are gone. by not firing it means the internal counter is not yet 0 so i would look for something in the code that still has a reference. in the days when object to integer handle conversion happened automatically, it was easy to have a memory leak because any int handle needed to be released in order to decrement the internal counter. if you didnt realize you did the conversion (usually because you failed to put a type on a variable declaration), you didnt know it needed to be released thus keeping object references around (and never firing the Delete() method). now fortunately, you need to use HandleFromObject() to get the integer handle so you know exactly what integer handles need to be released. as noel mentioned, i would highly recommend a single base type, including the mentioned dispose method, that all your types are ultimately based from. |