[Gambas-user] Help me understand "circular references" please

Benoît Minisini benoit.minisini at gambas-basic.org
Thu Nov 16 14:55:14 CET 2023


Le 16/11/2023 à 14:44, Bruce Steers a écrit :
> I hate these circular references.
> 
> Here's my classic scenario where a created object needs to know the 
> object that created it...
> 
> My Form1 class creates an object from another class. (Class1.class)
> The other class's methods need to know that Form1 called it because it 
> wants some of it's data so it's Parent must be noted.
> 
> So i create my object like this in Form1_Open().
> 
> Dim $hClass = New Class1(Me)
> 
> Class1.class looks like this in _new()
> 
> Private $hForm As Form
> 
> Public Sub _new(Parent As Form)
> 
>    $hForm = Parent
> 
> End
> 
> Now when the program closes i get this...
> 
> gbx3 [432764]: warning: circular references detected:
> gbx3:     1 Form1
> gbx3:     1 Class1
> gbx3 [432764]: warning: 3 allocation(s) non freed.
> 
> I've attached a very simple program to demonstrate the problem.
> 
> Here's what i want to know...
> A)  what causes this error?

You created circular references, and so the interpreter tells you.

Form1 object owns a reference to the Class1 object, and Class1 object 
owns a reference to the Form1 object. This is what is circular.

Consequently, the interpreter cannot free the two objects.

> B)  what's the recommend way to avoid it?

You must manually break the circular reference before exiting the 
program, by setting one of the two variables owning these reference 
($hForm or $hClass) to NULL.

> C) how should a created object safely know and access the parent object 
> that creates it?
> 

Often by making objet A parent of the object B and use Object.Parent(B), 
but it requires that B raises events, and A is its event observer. That 
way you don't need to store a reference to A in B, hence avoiding the 
circular reference.

Regards,

-- 
Benoît Minisini.



More information about the User mailing list