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

Bruce Steers bsteers4 at gmail.com
Thu Nov 16 16:13:34 CET 2023


On Thu, 16 Nov 2023 at 13:56, Benoît Minisini <
benoit.minisini at gambas-basic.org> wrote:

> 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.
>

aah , thank you Ben , i understand


> > 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.
>

Ahh that's a perfect solution.
Working a treat
I made a dummy event in Class1
Event _Dummy
created the object more like this..
Dim $hClass = New Class1 As "Whatever"

now Object.Parent(Me) in Class1 gives me what i needed :)
Thanks again :)
BruceS
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20231116/1e458c7f/attachment.htm>


More information about the User mailing list