Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I have a snippet of code below that

Status
Not open for further replies.

Cocheez

Programmer
Jun 6, 2001
56
US
I have a snippet of code below that as far as I know should not work but does. I have always thought that when you create an object within a function that object loses scope and automatically releases its memory once the function ends. In this case the function returns the reference, ends, and the calling function is able to use the reference with no problem. Can someone tell me why?


' Used for all server objects
Public oServer As Object

Private Sub DoSomething()
Set oServer = CreateAndReturnServerObject("Fin2k.clsClass", "")
msgbox oServer.GetKidCount
Set oServer = Nothing
End Sub

Private Function CreateAndReturnServerObject(svr_obj As String, URL As String) As Object
Dim genRDS As New RDS.DataSpace
Dim gen As Object

Set gen = genRDS.CreateObject(svr_obj, URL)
Set genRDS = Nothing
Set CreateAndReturnServerObject = gen
End Function
 
No, this definitely should work. Like strongm said, objects are destroyed once they have no references. However, in returning the object, you're creating a reference to it, so the reference count stays at 1. It would work the same way if you were to assign oServer = gen directly instead of through a function call. Either way, you're saving a reference to that object, so it won't be destroyed. Think of it this way: as long as some variable remembers the object exists (i.e. holds a reference to it), it will stay in existence. Once everybody has forgotten it's there, it'll be destroyed.
 
Thanks to both of you, that makes perfect sense.

-Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top