delete in max?

BlitzMax Forums/BlitzMax Programming/delete in max?

D4NM4N(Posted 2006) [#1]
eg.

for a:mytype=eachin mytype_Li
mytype_li.remove a
delete a<-------------How do i free this?!?
next


klepto2(Posted 2006) [#2]
You just have to look if there is no other reference to the object, then Blitzmax will free it automaticaly.


ziggy(Posted 2006) [#3]
you don't have to. all instances are automatically freed when there are no pointers pointing them. So if the objects in mytype_Li are only included in mytyle_Li collection, after the For / next structure, all of them are freed.

AS instance:

a = new MyType  'Create an instance pointed by the 'a' variable
a = null 'a no longer points to the previous instance, so the previous instance is deleted automatically.

If you have understood this, take in consideration the following example:
b = new MyType  'Create a new MyType instance pointed by b
c = b  'C points to the same MyType instance than b
b = null  'b no longer points to the MyType instance, but the instance is not deleted becouse C is still pointing it.


This is how reference counting works in BlitzMax. You don't have to destruct instances, you only have to leave them unpointed and they're automatically free.

Another important point. Avoid cross-referencing if you don't want to have unused unfree memory in your runing application. example of a bad design:

Type MyType1
    Field X:MyType2
end Type

Type MyType2
    Field Y:MyType1
end Type

'Create instances
a = new MyType1  'a points to a new instance of MyType1
b = new MyType2  'b points to a new instance of MyType2

'Assign cross references: (bad design)
a.X = b
b.Y = a

a = null  'MyType1 instance is not deleted becouse it is pointed by the Y field of the MyType2 instance.
b = null 'MyType2 instance is not deleted also, becouse it is pointed by the X field of the undeleted MyType1 instance.

This is something you should be very careful with.

You can add a Delete method in your TYPES. This method will be automatically called when a particular instance is free becouse there are no items pointing it. The calling to this method is not imediate, it can be called after a little while of the object is deleted automatically by the Garbage Collector (GC)


Hotcakes(Posted 2006) [#4]
Just to elaborate on ziggy's last sentences, you can not rely on your object being freed when you dereference it. The GC will pick it up and free it whenever it wants to...

The Delete method is called when the GC frees your object... this could happen straight away, or it might never happen... the GC knows when is the best time to free an object. So the Delete method must not be used for program critical stuff.