What will happen when I call this sub?
The object will be created, and a reference to it through TestObject will be created, and the reference count will be boosted to 1.
When TestObject goes out of existence, the reference count is dropped to 0. When garbage collection takes place, the memory will be reclaimed.
Because of this, you cannot rely on actions within the cObjectClass class to perform their finalizations just because the reference went away.
The Dispose method will run when the object is garbage collected, but you cannot know when that will be.
Setting to Nothing opens the door for that garbage collection, but nothing more (no pun intended).
Having or not a Dispose method makes no difference as to when the memory will be freed. If memory is needed, a GC will be triggered. This wway, the program is not slowed down by destroying objects every time they are no longer referenced, but only when memory is required.
When you run the two As New statements two objects are created, and a reference to each is created. They each have a reference count of 1.
Human2 = Human1 causes the obect that Human1 refers to to now have a reference count of 2, and causes the object that Human 2 used to refer to to now have a reference cout of 0âit can be destroyed upon GC. Human2.name = "Christopher," because it reads the same memory as was set and filled through Human1.
In your final example, the 2nd statement types the variable, but creates no objectâand it does not change the size of your program. Variable names are used in compilation, but do not exist in the actual code. If an object is not created, no memory for it is ever needed.
But, accordingly, if you then refer to Human2 in code, you will recieve object or block not initialized (or whatever). You will need to either do something like Human2 = Human1, where Human 1 is an initialized object, or Human2 = New cHuman. The original statement, having typed the variable will cause a compilation error if you try Human2 = New cUberMan. That is a different type. That typing is not useless, you see. Just because it creates nothing, doesn't mean it doesn't do anything for you.
Does that clarify?
|