Say I have two hypothetical classes: Stereo & Speaker:
brand as String
speakers() as Speaker
location as String
owner as Stereo[/code]
Speaker has a Constructor like so:
Sub Constructor( ownerStereo as Stereo, theLocation as String )
owner = ownerStereo
location = theLocation
If I wanted to add a speaker to the stereo I would do this:
[code]dim myStereo as new Stereo
dim aSpeaker as new Speaker(myStereo, “Kitchen”)
myStereo.brand = “Sony”
myStereo.speakers.Append( aSpeaker )[/code]
Will this create an awful circular reference or memory leak or is it OK for a Class to keep a reference to its “owner”. These are obvuiously fictitious classes designed to illustrate a point.
I’ve never had issues using the above design, but would also like to know if this is a good or bad design?
And if it’s bad, what would the right way be to implement such a stereo-speaker model?
It’s a circular reference. Make Speaker.owner a computed property. The private property type should be WeakRef. The computed property can create the WeakRef on set, and retrieve the value from the WeakRef on get. That way code which calls Speaker.owner never knows the difference but the circular reference is broken.
The circular reference takes place when there is logic to find something and the pointer in one part of the traversing sequence points to the other (or even itself) and the other points to the first so that the traversing never ends and goes in to an endless loop, like the binary trees where a node has the “pointer to next node” that happens to point to the same node or to a node that has already been traversed.
The example above in initial post seems to be the case when two elements (individuals or an instance of same or different class for example) have the reference to the other individual. So that the program logic, given the reference to one, can find the other and given the reference to the other can also find the first. Please also see the this.
Will this create an awful circular reference or memory leak or is it OK for a Class to keep a reference to its “owner”. These are obvuiously fictitious classes designed to illustrate a point.[/quote]
Yes it would since they both have a hard reference to each other
So if you were to abandon / orphan the reference to the stereo neither would be destroyed.
Using a weakref in the speakers class to refer to the stereo would NOT cause that to happen and then abandoning the stereo could cause it & the speakers to be destroyed correctly - unlike a couple house parties I had way back when where the speakers were improperly destroyed
Good info guys - WeakRef is it then
Norman, thanks for a great explanation. On a practical level, is the following then the correct way to handle “circular” references?
I have two classes, X3Model and X3Polygon.
Polygons() As X3Polygon
mParentModel As WeakRef
ParentModel As X3Model
ParentModel is a computed property with
mParentModel = New WeakRef(some model)