Excel VBA:破坏一个对象集合会毁掉每一个对象吗? [英] Excel VBA: Does destroying a collection of objects destroy every single object?
问题描述
说我有一个 MyClass
对象的集合 MyCollection
。
Say I have a collection MyCollection
of objects of MyClass
.
设置MyCollection = Nothing
调用每个包含的对象的析构函数或者应该注意设置每个对象 =没有
个别?
Does Set MyCollection = Nothing
call each contained object's destructor or should I take care of setting each object = Nothing
individually?
我显然关心内存泄漏的原因。
I obviously care for reasons of memory leakage.
Dim MyCollection As Collection
Set MyCollection = New Collection
... 'add objects of type MyClass here
Set MyCollection = Nothing
是否破坏此类调用每个对象的析构函数?
推荐答案
当您销毁MyCollection时,所有的MyClass对象都将被销毁,除非它们被其他地方引用。
All the MyClass objects will be destroyed when you destroy MyCollection, unless they are referenced somewhere else.
VBA使用类上的引用计数器。它每次都有一个类的引用,每当一个引用被销毁时,它会每次一个。只要MyCollection是某事并且在范围内,其中包含的每个MyClass引用计数器将至少是一个。如果引用计数器正好一个,破坏MyCollection会将每个元素的引用计数器减为零,并且将被垃圾回收。
VBA uses a reference counter on the class. It ticks up one every time there's a reference to the class and ticks down one every time a reference is destroyed. As long as MyCollection is something and is in scope, every MyClass reference counter contained therein will be at least one. If the reference counter is exactly one, destroying MyCollection will tick every element's reference counter down to zero and it will be garbage collected.
最后一个MyClass变量在你的sub将引用MyClass的一个实例,除非您明确将其设置为Nothing。一个类变量不太可能导致明显的内存问题。
The last MyClass variable in the middle of your sub will reference one instance of MyClass unless you explicitly set it to Nothing. One class variable isn't likely going to cause a noticeable memory problem.
Sub MakeClassColl()
Dim MyCollection As Collection
Dim i As Long
Dim clsMyClass As MyClass
Set MyCollection = New Collection
For i = 1 To 3
Set clsMyClass = New MyClass
MyCollection.Add clsMyClass
'Check1
Next i
Set MyCollection = Nothing
'Check2
End Sub
Check1:
- i = 1:MyClass1(实例1)的引用计数器为2.一个用于变量,一个用于集合
- i = 2:MyClass1 rc为1(丢失的clsMyClass,仍然有集合),MyClass2的rc为2
- i = 3:MyClass1仍然为1,MyClass2的rc为2 / li>
- i=1: MyClass1 (instance 1) has a reference counter of 2. One for the variable, one for the collection
- i=2: MyClass1 has an rc of 1 (lost clsMyClass, still has collection), MyClass2 has an rc of 2
- i=3: MyClass1 still 1, MyClass2 drops to 1, MyClass3 has an rc of 2
Check2:
- 每个MyClassi实例收集下降一个。 MyClass1和2转到零。 MyClass3下降到1,因为clsMyClass仍然引用它(我没有在将其添加到集合后销毁clsMyClass)。
这篇关于Excel VBA:破坏一个对象集合会毁掉每一个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!