Hi Ben,
Just to clarify, are you saying that in VB6 if you didn't de-reference an
object before it went out of scope, it would automatically be cleaned up
anyway? I'm not saying this in an accusatory manner, but everything I
ever
read in terms of good practice and even articles on MSDN seemed to imply
otherwise - in fact I can even remember it being touted as a selling
point
to upgrade to VB.NET.
Example (VB6):
Private Sub Test()
Dim objRef As SomeClass
Set objRef = New SomeClass
' ...
' ...
Set objRef = Nothing ' <--- Dereferencing before it goes out of scope
End Sub
Are you saying that the last line, "Set objRef = Nothing", was therefore
unneccesary in VB6?
Yes. It was and is completely unnecessary. Simple to prove to your
self -
just create a VB6 class and put some output in the class terminate event.
I was always under the impression that memory leaks
courtesy of objects that are still referenced (but out of scope) would
occur
if you did *not* de-reference before they went out of scope.
You had the wrong impression.
I could've
sworn there was even a Dr GUI article where he discussed using specific
Co*
API calls to increment/decrement references to objects in order to hack
up a
weak reference system in VB6, saying something like "the object reference
therefore still exists even when [not if] you Set objRef = Nothing at the
end of the Sub". The implied logic (at least my interpretation) was that
every VB6 coder should Set objRef = Nothing before said reference falls
out
of scope.
Most of these sort of hacks were created to deal with the issue of
circular
references. Circular references are a classic pain for ref counting
memory
managment.
Ref counting has the advantage of deterministic finalization - but GC has
better object allocation/deallocation performance and doesn't have issues
with
circular references. Of course, you also loose deterministic
finalization,
which means that you the developer have to be more aware of what unmanaged
resources you maybe holding on to...
If this is not the case, then apparently VB6 was a bit smarter than I
gave
it credit for!
You have been indoctrinated into the myth that memory managment in
VB.CLASSIC
is some how difficult. It isn't, except for a couple of cases - module
level
values and circular references - the programmer does NOT need to set an
object
to nothing. VB automatically calls release on objects as they fall out of
scope.
Again the quote from Bruce McKinney in "Hardcore Visual Basic" (one of my
all
time favorite VB books!):
<quote>
In real Visual Basic code, references are rarely destroyed
explicitly by setting an object variable to Nothing. Instead,
objects are created and destroyed automatically when you
pass objects to procedures, return them from functions, set or
get them with properties, or destroy other objects that hold
references to them.
</quote>