出于调试原因,我想销毁一个仍然作为引用的类实例。那可能吗?它不一定非常优雅或稳定,因为它永远不会以生产代码结束。
澄清:
Public Sub Main
Dim o as MyClass
Set o = New MyClass //o is created, one reference
DestroyObject o //Class_Terminate is called and the object destroyed
//Further code, not using o
End Sub //Possible runtime error here (don't care)
这可能吗?一种方法是调用IUnknown::Release
手动减少引用计数,但我现在应该多久调用一次?
答案 0 :(得分:3)
这是一个非常糟糕的主意
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private m_oRef As Class1
Private Sub Command1_Click()
Dim o As Class1
Set o = New Class1
Set m_oRef = o
DestroyObject o
' releasing m_oRef after this point will bring down the IDE '
End Sub
Private Sub DestroyObject(pArg As Object)
Dim lRefCount As Long
Dim lIdx As Long
Dim pUnk As IUnknown
lIdx = ObjPtr(pArg) + &H20
Call CopyMemory(lRefCount, ByVal lIdx, 4)
For lIdx = 1 To lRefCount - 2
Call CopyMemory(pUnk, pArg, 4)
Set pUnk = Nothing
Next
Set pArg = Nothing
End Sub
答案 1 :(得分:1)
如您所知,对象本身会在认为其引用计数为零时调用Class_Terminate
,因此您调用Release
的建议应该可以解决问题 - 只需继续调用{{1}直到Release
本身抛出错误。
This page from Bruce McKinney's Hardcore Visual Basic建议一种可能的方式,有时可能获得引用计数,但我不认为你需要进入,除非这个方案(Release
直到你可以“不再Release
”不起作用。
“这将永远不会以生产代码结束” - 当然要小心你的假设......