Danger of null List Items?
BlitzMax Forums/BlitzMax Programming/Danger of null List Items?
| ||
Take the following code:Type TIniLine Field Name$ Field Value$ End Type Type TIniFile Extends TList Field FileName$ 'full filepath (or relative path) Method Add(name$,value$) Local Line:TIniLine = New TIniLine Line.Name = name Line.Value = value Super.AddLast(Line) End Method Method Save() Local file:TStream=WriteFile(FileName) If Not file RuntimeError("Failed to open file "+FileName) Local Line:TIniLine 'Create a file, overwriting any that already exists For Line = EachIn Self WriteLine file,Line.Name+"="+Line.Value Next CloseStream file End Method End Type In the Add method, you can see that I an constucting a Local Line from the parameters passed in and then adding this to the list. It DOES seem to work, but if the garbage collector got hold of the local variable once the function was finished, could it free up the Local Line variable and thus the list would be pointing to a Null variable? Or won't the garbage cleaner clean it because it knows the list is using it, and then when the list is finally freed, it will clean up all the Local Line variables that were made. Is this how it works? Perhaps there is a better way. Any comments? Thanks. |
| ||
Some of the BRL modules do things like this. As long as an object is still referenced, it shouldn't be freed. |
| ||
Or won't the garbage cleaner clean it because it knows the list is using it, and then when the list is finally freed, it will clean up all the Local Line variables that were made. Is this how it works? Yes, that's how it works. You'd probably want to ask FlameDuck or one of the most experienced OO programmers, but it's my understanding that if you're using the purest OO design, you rarely have references to specific objects. The purpose of OO design is that objects should be self-contained, and you should therefore not need to handle them outside the object. In my GUI I'm currently writing, I have no handles to any of the GUI gadgets. They're held in one ( or more ) lists and when the gadget is freed, they automatically remove themselves from every list they're in. Thus they will be cleaned up by the GCC when it's ready. |
| ||
When you call the Add method and create the local line:TIniLine, bmx should have a reference count of 1 for that variable. When it's added to the list the reference count gets added to making it 2. When you leave the Add method there is no longer a reference to the local (as it's a local) so the count gets decremented to 1. In short, the way you're doing it is the best way to go about it. |
| ||
Thanks everyone. I thought it was the correct way to go but wanted to make sure before it blew up in my face later on :) |