digitalmars.D.learn - shallowCopyFrom: how to shallow copy objects / swap contents ?
- Timothee Cour via Digitalmars-d-learn (33/33) Feb 13 2015 Is there a standard way to shallow copy objects?
Is there a standard way to shallow copy objects? eg: class A{ int* a; string b; } unittest{ auto a=new A; a.a=new int(1); a.b="asdf"; auto b=new A; b.shallowCopyFrom(a); assert(b.a==a.a); assert(b.b==a.b); } How about: option A1: void shallowCopyFrom(T)(T a, T b) if(is(T==class)){ size_t size = b.classinfo.init.length; (cast(void*) a)[8 .. size] = (cast(void*) b) [8 .. size]; } Is this guaranteed correct? option A2: auto shallowCopyFrom(T)(T a, T b) if(is(T==class)){ foreach (name; __traits(allMembers, T)) { enum temp="a."~name~"="~"b."~name~";"; static if(__traits(compiles, mixin("{"~temp~"}"))) { mixin(temp); } } } option A2 has issues with property, though. option A1 should also be adaptable to swapping contents.
Feb 13 2015