Click to See Complete Forum and Search --> : Class objects


rghthnrblmrc
12-14-2006, 11:28 AM
Since I am new to VBScript, I wanted to know about instantiating and destroying objects, and whether what I am doing is necessary in order to clear out memory spaces. I read somewhere that every time an instance of an object is done being used, the symbol that points to it needs be set to nothing. Is this true even as an object falls out of scope?

For instance, say I have a subroutine A() that instantiates [instance c of] an object B:

Class B
Private Sub Class_Initialize
End Sub

Private Sub Class_Terminate
End Sub

Public Sub SayHello
Response.Write("Hello World")
End Sub
End Class

Sub A
Dim c
Set c = New B
c.SayHello
Set c = Nothing ' **
End Sub

A

**Is this line actually necessary, or will the object terminate simply by falling out of scope, since it is pointed to by a variable local to the subroutine?

I believe that it is required, from what I have read, but i want to double-check. If it is required, what will happen if i do not do it? Will it eventually crash ASP? thanks.

so_is_this
12-14-2006, 11:34 AM
I'm not 100% certain but, I believe only the variable c falls out of scope -- not the object. The variable is only a pointer to the object and not the object itself. Thus, the pointer to the object is dropped (when out of scope) but the object remains.

russell
12-19-2006, 09:34 PM
it will go out of scope and eventually be destroyed when the script finishes executing. of course this is bad practice -- all object variables should explicitly be destroyed immediately after using them. why? on a high traffic site, we are wasting memory when we fail to destroy our objects. also, no gurantee exactly when garbage collector will clean up ( though it is almost always immediate )

rghthnrblmrc
12-20-2006, 10:03 AM
Thanks—a follow-up question:

Does the statement Set c = Nothing actually destroy the object if there are multiple pointers to it? Consider this example:

Dim d(2), e, f

Set e = New B
Set f = New B

Set d(0) = e
Set d(1) = f

Set e = Nothing
Set f = Nothing

Since I put a pointer to the instances [pointed to by] e & f into array d prior to setting them to nothing, will their instances be preserved when the originals are destroyed, even only the object's reference is placed in the array, capice?

russell
12-20-2006, 10:42 AM
won't destroy it. consider

Class B
Private ttt

Private Sub Class_Initialize()
ttt = 3
End Sub

Public Function getTtt()
getTtt = ttt
End Function
End Class

Dim d(2), e, f

Set e = New B
Set f = New B

Set d(0) = e
Set d(1) = f

Set e = Nothing
Set f = Nothing

Response.Write d(0).getTtt()
displays 3

thus we need to destroy ALL object variables