Copy Object

BlitzMax Forums/BlitzMax Programming/Copy Object

maverick69(Posted 2007) [#1]
Is there an easy way to create a new copy of an object with exactly the same values, without knowing it's type structure?

As I understand the following code creates a pointer to the original object:

Type MyObject
  Field X:Int, Y:Int
End Type

Local A:MyObject = New MyObject
A.X = 10
A.Y = 20

Local B:MyObject = New MyObject
B = A

B.X = 100

DebugLog A.X 'Output: 100



ziggy(Posted 2007) [#2]
It is not possible. The only way would be to make a base class with and abstract clone method, and make all your app object derive from this base class. take in consideration that you will have to implement the clone method for every type you create, and you will have to deal with pointers to other classes.

The most problematic part of all this is how you clone this:

Type A Extends Clonable
    Field MyField:OtherType
    Method Clone()
        .
        .
        .
    End MeThod
End Type

Type OtherType Extends Clonable
    Field Whatever:A
    Method Clone()
        .
        .
        .
    End MeThod

End Type

Local MyVariable:A = New A
A.MyField = New OtherType
A.MyField.Whatever = A

Local MyOtherVariable:A = MyVariable.Clone()


The main problem here is how to clone Type A, as one of its fields points to another type instance. Should this be cloned too? if it is cloned, you could enter a infinite loop and make memory needs grow unpredictabily. If it is not cloned, you have only a partial 'copy' of the original object, so you will have to know what fields of your class are really cloned and what others are not. Not a real solution, and most important, not an 'automatic' solution.


Suco-X(Posted 2007) [#3]
Ups, please remove.


Suco-X(Posted 2007) [#4]
Hi maverick69
This code could be a solution for you.



Seems to be working.
Mfg Suco


ziggy(Posted 2007) [#5]
@Suco-X: This can confuse the GC as you're coping pointers without letting the GC know it, it works, but it is a little bit dangerous. Spetially the field called Other, you copy the reference to it, but the reference counting is not updated on the GC. This can confuse also the GC using string variables inside types.


tonyg(Posted 2007) [#6]
You'd have to be careful of memory leaks as GC won't remove the object fully... I think.


maverick69(Posted 2007) [#7]
thanks