shallowCopyFrom: how to shallow copy objects / swap contents ?

Timothee Cour via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 13 18:42:23 PST 2015


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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150213/b14266ed/attachment.html>


More information about the Digitalmars-d-learn mailing list