Type safety

Previous topic - Next topic

MrTAToad

No pun intended :)

How safe is this :

Code (glbasic) Select
TYPE TTest
a%

FUNCTION yes AS TTest:
LOCAL moo AS TTest

self.a%=16
moo.a%=19
RETURN moo
ENDFUNCTION

FUNCTION exit%:
RETURN self.a%
ENDFUNCTION
ENDTYPE

LOCAL t AS TTest

t=t.yes()
DEBUG "t.a% ="+t.a%+"\n"
DEBUG "t.a% = "+t.exit()+"\n"


Compiles and runs okay, values return are valid, and I presume the value return from t.yes overwrites the original value of t...

It's not something I would recommend doing anyway, but all knowns need to be known, otherwise you'll have unknowns that are not known...

Ian Price

I came. I saw. I played.

matchy


MrTAToad

There are some known unknowns there!

hardyx

You use a function that modify the type (instance) and returns another type. Then, in the calling code you assign the result to the same object. I can't imagine a real case that can be useful with this code. Is a good code for programming skill tests anyway. :)

MrTAToad

Indeed - its bad form :)

MrTAToad

No, was just wondering what the executable would do...

Kitty Hello

that one took me a while to get what you are/it is doing.  :blink:
But it's doing "well".

t.yes assigns the self.a with 16 and returns a type with a=19.
Then you assign that 19 type to "self", overwriting the 16.


XanthorXIII

Here's a problem though, Executable wise it's fine but what about memory? If you create an object, then run a function that creates another object and returns that object reference reassigning it's address to the first object, what happened to the original object?
I could be wrong with my limited knowledge of GLBasic(I'm still in the shallow end of the pool)

Owlcat has wise

MrTAToad

Yes indeed - will the original type be destroyed when the new type is returned, or is it still in memory with the creation of a new type ? Or even, perhaps the new type overwrites the memory of the old one :)

XanthorXIII

Testing this, I couldn't find a memory leak. Seems like ether Windows 7 or GLBasic has very good memory handling!

Code (glbasic) Select
TYPE TTest
   a

   FUNCTION yes AS TTest:
   LOCAL moo AS TTest
      self.a=1600000000
      moo.a=1900000000
      RETURN moo
   ENDFUNCTION

   FUNCTION exit:
      RETURN self.a
   ENDFUNCTION
ENDTYPE

LOCAL t[] AS TTest
   DIM t[20000]
   FOREACH Test IN t[]
    Test=Test.yes()
    DEBUG "t.a = "+Test.a+"\n"
    DEBUG "t.a = "+Test.exit()+"\n"
   NEXT
Owlcat has wise

Kitty Hello

You can't do memory leaks on GLBasic.
What's it doing here?

LOCAL t AS TTest - one instance of TTest

t.yes() // internally creates another instance (moo) of TTest
the return value will copy the the moo to the lparam (if any given)
in this case:
   t=t.yes()
the local moo is copied over the t.
After the copy the local moo will be dropped from the stack.

XanthorXIII

Kitty,
Thank you for the explanation on this one. I was wondering myself.

Owlcat has wise

MrTAToad

Yes, it solves that problem :)