Where did variable = null as “object destroying” come from?

后端 未结 14 1845
无人共我
无人共我 2021-02-18 15:51

Working on a number of legacy systems written in various versions of .NET, across many different companies, I keep finding examples of the following pattern:

pub         


        
14条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-18 16:28

    It is possible that it came from VB which used a reference counting strategy for memory management and object lifetime. Setting a reference to Nothing (equivalent to null) would decrement the reference count. Once that count became zero then the object was destroyed synchronously. The count would be decremented automatically upon leaving the scope of a method so even in VB this technique was mostly useless, however there were special situations where you would want to greedily destroy an object as illustrated by the following code.

    Public Sub Main()
      Dim big As Variant
      Set big = GetReallyBigObject()
      Call big.DoSomething
      Set big = Nothing
      Call TimeConsumingOperation
      Call ConsumeMoreMemory
    End Sub
    

    In the above code the object referenced by big would have lingered until the end without the call to Set big = Nothing. That may be undesirable if the other stuff in the method was a time consuming operation or generated more memory pressure.

提交回复
热议问题