2010-06-01 23 views
0

由于调试的原因,我想销毁仍然作为参考的类实例。那可能吗?它不一定是优雅或稳定的,因为这永远不会在生产代码中结束。即使仍有引用,我可以销毁一个类实例吗?

澄清:

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手动减少参考计数,但我现在该如何经常调用它?

回答

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

如你所知,对象本身将调用Class_Terminate当它认为它的引用计数已经得到了零,所以您的通话Release应该做的伎俩的建议 - 只要保持通话Release直到Release本身抛出一个错误。

This page from Bruce McKinney's Hardcore Visual Basic提出一种可能的方式,这可能有时可能得到的引用计数,但我不认为你需要进入,除非这个计划(的Release ING直到你不能Release没有更多)没有按没有工作。

“这永远不会在生产代码落得” - 小心你的假设,当然,...

+0

当然,因为这不需要超稳定释放,直到错误完全正常。 – 2010-06-01 07:48:27

+0

您链接到的引用计数代码完美工作,即使在VB6中。坏消息:VB编译器捕获到Release的调用。我想我需要另一种解决方法。 – 2010-06-01 08:00:51

相关问题