How to dispose of a class instance?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
Relayer
Posts: 160
Joined: 30 Sep 2013, 13:09
Location: Delaware, USA

How to dispose of a class instance?

14 Sep 2017, 12:33

I have a class that will be instantiated many times where those instantiations may become unused but continue to pile up new ones thus wasting resources. What is the proper way to dispose of an instance? Do you use a method in the class to destroy an instance by simply calling it via that instance? Is this what __Delete() is for? If so, what exactly triggers the execution of that meta function? Thanks in advance.

Relayer
Helgef
Posts: 4709
Joined: 17 Jul 2016, 01:02
Contact:

Re: How to dispose of a class instance?

14 Sep 2017, 12:57

Hello. You simply release your last reference to the object to trigger a call to __delete and when that function returns, ahk will free it. See reference counting. Simple example,

Code: Select all

a:=new test ; creates one reference to the new "instance" of test
a:="" ; __delete

a:=new test
b:=a	; There are now two references to the object 
a:="" ; no __delete
msgbox no __delete
b:="" ; __delete - since the last reference was released

class test {
	var:=1
	__delete(){
		msgbox delete
	}
}
In __delete you should do things like delete files you have written to disk, release handles or memory you have allocated manually via dllcall. Maybe destroy a gui or whatever you like. Regular instance variables, like var:=1 in the example above, ahk handles for you.

Cheers.
User avatar
Relayer
Posts: 160
Joined: 30 Sep 2013, 13:09
Location: Delaware, USA

Re: How to dispose of a class instance?

14 Sep 2017, 14:44

Helgef,

That's what I thought. Where I went wrong is that I was storing every instance in an class variable array which was inhibiting the call of __Delete(). Once I deleted that reference my meta function worked. Thanks for knocking me up-side the head!

Relayer

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Google [Bot] and 250 guests