Struct copy, how?
BCS
ao at pathlink.com
Fri Jan 2 20:26:56 PST 2009
Reply to nobody,
> (D 1.0)
>
> After some problems with my program I found where my problems arose.
>
> In my mini example: A function that is supposed to create a new bear
> from 2
> exisiting bears ends up altering the original bears.
> I suspect it has to do with the line ' Bear newBear = bear1;', in that
> it
> doesn't copy the contents of the struct.
> Is there a way to copy a struct without resorting to iterating over
> all its
> elements manually?
I think you almost spotted the cause. Bear contains an array (a reference
type) of Claws. When you copy it you get a new struct with a copy of that
array (again a reference). Because that array is a reference type it still
referees to that same set of Claws. You can fix this by copying/duping the
array
Bear newBear = bear1;
newBear.claw = bear1.claw.dup;
IIRC struct now have an opAssign that can burry this in the struct code rather
than the client code.
However this still has a few problems: 1, if claw contains a reference type
you will now have 2 Claws that refer to the same thing and 2, you need to
maintain opAssign to be sure that it copies all members.
One way to attack both of these would be to use a template to build a generic
deep copy that uses compile time refection to copy all the members, duping
arrays of PODS, copying basic types and recursively deep copying reference
types and arrays of them.
More information about the Digitalmars-d-learn
mailing list