Private obj As clsClass1

Public Property Set Link(objMyObject As clsClass1)

'Create a link from this object to the other one Set obj = objMyObject

Debug.Print "Creating reference to clsClass1 from clsClass2" End Property

Private Sub Class_Initialize()

Debug.Print "Instantiating clsClass2" End Sub

Private Sub Class_Terminate()

Debug.Print "Terminating clsClass2 instance" End Sub

Then add the following procedure to a standard module:

Public Sub TestVariableLifetime() Dim objMyObject1 As clsClass1 Dim objMyObject2 As clsClass2

'Instantiate the two object variables Set objMyObject1 = New clsClass1 Set objMyObject2 = New clsClass2

'Create a link to one object from the other Set objMyObject2.Link = objMyObject1

'Destroy the local object references Set objMyObject1 = Nothing Set objMyObject2 = Nothing End Sub

Take a look at the TestClassLifetime procedure. If you step through the procedure line by line (by successively pressing F8), the debug window tells the real story.

The procedure begins by creating the two class objects: objMyObject1 and objMyObject2. The code then sets a second pointer to objMyObject! in objMyObject2 (see Figure 12-18).

Figure 12-18

Despite the fact that the first local pointer to clsClass1 (objMyObject1) is then set to Nothing, you will see that the object itself is not destroyed until after objMyObject2 passes away. Why? Because the second pointer still exists after the demise of the first pointer, so the object itself remains alive.

When the pointer to clsClass2 is destroyed, its pointer to clsClass1 is also destroyed, thereby releasing the clsClass1 object. But that's not the worst that can happen. If we change TestClassLifetime() by setting a reference to clsClass2 from clsClass1, a circular reference is created.

'Create a link to one object from the other Set objMyObject2.Link = objMyObject1 Set objMyObject1.Link = objMyObject2

Run the procedure to see what happens. Neither object is destroyed. Why? Because each object maintains a reference to the other. Once such code is executed, both objects remain in memory until the application is shut down; there is no way to programmatically terminate them (see Figure 12-19).

Figure 12-19

So how do we avoid such things from happening? Well, you must explicitly terminate each inner reference before destroying the outer reference. This is accomplished by adding the following method to each class:

Public Sub TerminateLink()

'If the object exists, destroy it If Not obj Is Nothing Then

Set obj = Nothing End If End Sub

Then we add the following two lines to TestClassLifetime() :

objMyObject1.TerminateLink objMyObject2.TerminateLink

0 0

Post a comment