"BCS" <[email protected]> wrote in message news:[email protected]... > 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
Oh I see. I find it a bit odd that it's copied in this manner, but I bet there's good reasons for it. Totally unexpected to me though :) > > 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. Is opAssign available in D1.0? > 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. > > Guess I'll do that. Thanks for the help!
