将变量设置为新对象时,VBA对象是否被破坏? [英] Is a VBA object destroyed when the variable is set to a new object?

查看:93
本文介绍了将变量设置为新对象时,VBA对象是否被破坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有找到针对该问题的答案,因此希望有人可以为我清除它.

I haven't found an answer specific to this question so hopefully someone can clear it up for me.

我了解VBA垃圾收集器使用引用计数来确定是否不再需要对象,并明确取消使用的变量的关联(从而减少引用计数):

I understand the VBA Garbage Collector uses a reference count to determine if an object is not longer required, and to explicitly disassociate a variable (thereby decrementing the reference count) you use:

Set objectVariable = Nothing

这是我目前正在使用的电子表格中的内容:

Here is what I have in a spreadsheet I'm working on right now:

Declare Function GetObject Lib "ObjectCreator.dll" () As Object
Public MyObject as Object

Sub MyMethod()
    Set MyObject = GetObject()
        ...do stuff with MyObject...

    Set MyObject = GetObject()
        ...do stuff with my new MyObject...

    Set MyObject = GetObject()
        ...do stuff with my even newer MyObject...

    Set MyObject = Nothing
End Sub

我的问题是:创建的所有三个对象都被GC破坏还是仅被最后一个破坏?即,当一个对象的引用变量设置为另一个对象而不是设置为Nothing时,该对象的引用计数是否会减少?

My question is: Do all three of the created objects get destroyed by the GC or only the last one? i.e. Does the reference count of an object get decremented when its referencing variable is set to another object rather than being set to Nothing?

推荐答案

将对象引用分配给变量时,引用计数增加1,而变量由于其他分配而失去引用时,对象的引用计数减少一.例如:

When you assign an object reference to a variable, the reference count goes up by one, and when the variable loses the reference by some other assignment, the object's reference count goes down by one. For example:

Dim a As Collection
Set a = new Collection 'The reference count of this new Collection object is 1
Set b = a              'The reference count of the Collection object is now 2
Set b = new Collection 'The reference count of the original collection has gone back down to 1 because b is no longer a reference to it, and this new Collection has a reference count of 1

Set a = Nothing        'The original collection no longer has any active references, so VBA safely GCs it.
Set b = Nothing        'The newer collection now no longer has any active references either, so VBA safely GCs it.

现在,在您的情况下,您正在谈论的是外部DLL,该DLL可能在内部以不同的方式管理其自身的内存或运行状态.但是VBA处理COM引用计数的方式是相同的.

Now, in your case you're talking about an external DLL, which may manage its own memory or running state differently internally. But the way that VBA handles COM reference counts is the same.

这篇关于将变量设置为新对象时,VBA对象是否被破坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆