Copy a TYPE (object)

General FreeBASIC programming questions.
Post Reply
Munair
Posts: 1286
Joined: Oct 19, 2017 15:00
Location: Netherlands
Contact:

Copy a TYPE (object)

Post by Munair »

I did a search here in the forum but could not find an explicit answer.

If I want to fully copy a TYPE rather than creating a second reference to the same TYPE, does the compiler do that for me with:

Code: Select all

bTypeCopy = aType
or would it require a Cast construction?
Munair
Posts: 1286
Joined: Oct 19, 2017 15:00
Location: Netherlands
Contact:

Re: Copy a TYPE (object)

Post by Munair »

Thanks that's a great thing. So if I understand correctly assigning one type (object) instance to another actually creates a new copy, rather than a copy of the same reference. This example seems to indicate that this is indeed the case:

Code: Select all

type aType
	x as integer
end type

dim as aType a, b

a.x = 5

b = a
print b.x

a.x = 2
print b.x 'still 5
end
So in order to create a new reference (for whatever purpose) one needs to explicitely copy the pointer. In RealBasic it was the opposite forcing one to manually copy each member. PureBasic has CopyStructure() to achieve the same thing.
D.J.Peters
Posts: 8586
Joined: May 28, 2005 3:28
Contact:

Re: Copy a TYPE (object)

Post by D.J.Peters »

if you need a "deep" copy you can overload "=" with let.

by the way you can view the translated FreeBASIC program as C-code or as assembler listing

asignment of a struct is a memcpy(target,source,sizeof(user_type))

Joshy
Munair
Posts: 1286
Joined: Oct 19, 2017 15:00
Location: Netherlands
Contact:

Re: Copy a TYPE (object)

Post by Munair »

OK, thanks
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Copy a TYPE (object)

Post by fxm »

Another variant is to make a copy-construction ('b') from the first instance ('a') after its initialization:

Code: Select all

type aType
   x as integer
end type

dim as aType a

a.x = 5

dim as aType b = a
print b.x

a.x = 2
print b.x 'still 5

sleep
Post Reply