Returning a local variable created with New

BlitzMax Forums/BlitzMax Programming/Returning a local variable created with New

ahobbit(Posted 2008) [#1]
Is it never a good idea to use as a return value, a reference to an object created inside a function from a local variable?

If the return value of the function is assigned to, let's say a global variable, will the reference to the return value still be valid when the function exits, or since the local variable is now referenced by a global pointer, will it remain valid after the function exits?

Example:

Function CreateNewAwesomeThing:TAwesomeThing()
    local awesome:TAwesomeThing = New AwesomeThing
    ...
    return awesome
End Function

global g:TAwesomeThing = CreateNewAwesomeThing()


Is g valid after the function exits (and therefore the local variable awesome is eventually garbage-collected)?

(I'm trying to interface with the API from an external DLL and occasionally need to create object instances inside functions which are passed as return values to mirror the API behavior in BMax).


plash(Posted 2008) [#2]
As long as there is a reference to the object it will not be removed; the Local variable will be Nullified once it is out-of-scope, g will essentially 'take over' the return/local object.


Gabriel(Posted 2008) [#3]
Yes, g is valid. The local variable awesome will not be collected, because it's reference count is not zero. The key word in Plash's reply is "reference". Remember that object variables are just pointers to the actual object. Objects are not collected by pointer, but by the object itself. All the time you have one pointer to that object, it will not be collected. That pointer may be in a list or a tmap, a global variable, a local variable, an array, anything.


H&K(Posted 2008) [#4]
Awesome is given a pointer in the function, then that pointer is given to G, so athough awesome itself is nolonger valid, the variable space it pointed to has always been pointed to by something, hence it still exists.


In some ways it is better practice to never have a "new" statement in the main code body.


Brucey(Posted 2008) [#5]
In some ways it is better practice to never have a "new" statement in the main code body.

Depends on your coding style, perhaps.

I like doing things like this :
Local myObject:TSuperClass = New TMySubClass.Create()

where Create() could be a method on a superclass...
Type TSuperClass

   Method Create:TSuperClass()
       ...

       Return Self
   End Method
End Type

Type TMySubClass Extends TSuperClass

End Type

Which tends towards a more OOP style of coding.


ahobbit(Posted 2008) [#6]
Thanks for the replies everyone.

It is a big relief to find out it is possible to create references to objects in this way. I thought I was going to have to rewrite a lot of code.