0

i have a question about destroying object from standard and custom classes through array, here is example:

dim class1 As cClass1
dim class2 As cClass2
dim class3 As cClass3
....

Set class1 = New cClass1
Set class2 = New cClass2
Set class3 = New cClass3
....

after using them i want to destroy them at the end to release them from memory, but i want to avoid usage of

Set class1 = Nothing 
Set class2 = Nothing 
.... 'and so on

i want to destroy them with:

CRLS Array(class1, class2, class3, "and so on")

and here is sub that might do that:

Private Sub CLRS(ByRef arr As Variant)
    Dim i As Integer
    For i = 0 To UBound(arr)
        If Not arr(i) Is Nothing Then
            Set arr(i) = Nothing
            Debug.Print "Deleted" 'it will throw "Deleted" but it will not delete element itself
        Else
            Debug.Print "not deleted" 'just to see status of element
        End If
    Next
    Erase arr
End Sub

but unfortunately, if i check if "destroyed" elements are really free, answer is not, only copy of selected elements was set to nothing. objects are passed to array just as ByVal.

tsolina
  • 141
  • 15
  • Why? They'll be released when they go out of scope, you don't need to manually release them in most circumstances – SWa Sep 18 '13 at 14:16

1 Answers1

0

VBA destroys objects by using reference counters. When the object reference count is zero, the object gets destroyed. Say for your class1 variable you increase the counter by one by setting it in:

Set class1 = New cClass1

Then you pass the object to the array.

Array(class1, class2, class3, "and so on")

The object reference count becomes two because now the array has its own reference. Then you set the array reference to nothing and the count is one because class1 still has the reference.

evpo
  • 2,436
  • 16
  • 23