Copy Object

BlitzMax Forums/BlitzMax Programming/Copy Object

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


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.

Ups, please remove.

Hi maverick69
This code could be a solution for you.

Strict

Type TTest
	Field X:Float, Y:Float
	Field Str:String[2]
	Field Other:TTest
End Type

Local ATest:TTest = New TTest
ATest.X = 100
ATest.Y = 200
ATest.Str[0] = "This is a test"
ATest.Str[1] = "Moep moep"
ATest.Other = New TTest
ATest.Other.X = 400
ATest.Other.Y = 2300


Local ATestCopy:TTest = TTest(Copy(Atest))
Print ATestCopy.X
Print ATestCopy.Y
Print ATestCopy.Str[0]
Print ATestCopy.Str[1]
Print ATestCopy.Other.X
Print ATestCopy.Other.Y


Function Copy:Object(Test:Object)
	Local Temp:Object
	Temp = New Test
	MemCopy(Temp, Test, SizeOf(TTest))
	Return Temp
End Function


Seems to be working.
Mfg Suco

@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.

You'd have to be careful of memory leaks as GC won't remove the object fully... I think.

thanks