2

我发现这里的主题回答了一半的问题: Scripting.Dictionary 的 RemoveAll() 方法是否首先释放其所有元素?

在我的例子中,值是 Dictionary 的实例,所以我有 Dictionary 对象的嵌套层次结构。

我的问题是我是否需要在每个子词典上调用 RemoveAll ?

' just for illustration
Dim d As Dictionary
Set d = New Dictionary

Set d("a") = New Dictionary
Set d("b") = New Dictionary

' Are the next section of code necessary?
' -------------------- section start
Dim key As Variant
For Each key In d
    d.Item(key).RemoveAll
Next
' -------------------- section end

d.RemoveAll
Set d = Nothing
4

3 回答 3

0

Consider this code

Option Explicit

Private m_cCache As Collection

Private Sub Form_Load()
    ' just for illustration
    Dim d As Dictionary
    Set d = New Dictionary

    Set d("a") = New Dictionary
    Set d("b") = New Dictionary

    d("b").Add "c", 123
    SomeMethod d

    ' Are the next section of code necessary?
    ' -------------------- section start
    Dim key As Variant
    For Each key In d
        d.Item(key).RemoveAll
    Next
    ' -------------------- section end

    d.RemoveAll             '--- d("b") survives
    Set d = Nothing         '--- d survives

    Debug.Print "main="; m_cCache("main").Count, "child="; m_cCache("child").Count
End Sub

Private Sub SomeMethod(d As Dictionary)
    Set m_cCache = New Collection

    m_cCache.Add d, "main"
    m_cCache.Add d("b"), "child"
End Sub

Without cleanup section d("b") will be virtually untouched -- neither children removed, nor instance terminated.

于 2012-12-19T10:17:36.703 回答
0

在 VB6 中,所有对象(通过 COM)都受到引用计数,因此,除非有循环,否则您不需要手动处理。

于 2012-12-30T07:06:36.947 回答
0

好的,我想我可以用我做的下一个测试来回答自己。

Sub Main()
  Dim d As Dictionary
  Dim i, j As Integer
  Dim sDummy As String * 10000
  For i = 1 To 1000
    Set d = New Dictionary      ' root dict.
    Set d("a") = New Dictionary ' child dict.
    For j = 1 To 1000
      d("a").Add j, sDummy
    Next j
    'd("a").RemoveAll
    d.RemoveAll
    Set d = Nothing
  Next i
End Sub

我注释掉d("a").RemoveAll(我的子字典)并且没有任何内存泄漏。这意味着调用RemoveAll根 ( d) 就足够了,这就是我需要知道的全部内容。

于 2012-12-19T21:35:24.773 回答