Copy Instance of an Object?

BlitzMax Forums/BlitzMax Programming/Copy Instance of an Object?

BLaBZ(Posted 2010) [#1]
Is it possible?

I found this code..
Type mytype
	Field val:Int
End Type

Local m:mytype,k:mytype
Local convert:Byte Ptr
Local size:Int

m = New mytype
m.val = 10
convert = m
size = SizeOf(m)

MemCopy (Byte Ptr(k),convert,size)


Print k.val

Delay 2000


Could this cause a memory leak in any way?


therevills(Posted 2010) [#2]
Check this thread:

http://www.blitzbasic.co.nz/Community/posts.php?topic=82368#928578

and this one:

http://www.blitzbasic.com/Community/posts.php?topic=73573#822043


Czar Flavius(Posted 2010) [#3]
It's a bit of work but it's safer to write your own clone or copy method for objects. The tricky thing is, what happens about references? Let's say your player has a TList field that contains all its bullets (for example). When you copy the player, the new player should have a new instance of TList otherwise the two players will share the same bullets! These are the kinds of questions you need to ask when copying an object - what object fields should still refer to the same thing, and which should refer to new object instances - that you can answer only in your own copy method.

For types that contain only basic data (ints etc) then the memcopy method might be ok as this problem doesn't arise. As for the memory leak question, I've never used the method so I don't know. Hopefully those links can answer it for you :)


Who was John Galt?(Posted 2010) [#4]
I would do a memcopy, then manually assign any fields that are pointers (i.e. pointers, string references, type references), so that the garbage collector is notified.. When you do this, as Czar said, you need to consider whether you are going to make a copy of the referenced object and point to that, or whether you just share the existing object.