How to realize copyable/postblit class

SimonN via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 12 22:20:38 PDT 2015


Hi,

I have a few classes with need for deeper copying. I don't want a 
bitwise copy necessarily. Ideally, I'd implement this(this).

I've thought about changing them to struct. However, the type 
feels much more like a D class than a D struct. It's often passed 
by reference, and it's not plain old data. Changing it to struct 
for the sole benefit of "this(this)" seems to be a bad tradeoff.

(Use case: Backing up game states in a for 
savestating/networking.)

I've resorted to a C++-style copy constructor:

this(T rhs) {
     myvalue = rhs.myvalue;
     myarray = rhs.myarray.dup;
     // ...
}

Downside: Boilerplate, each member appears once in the 
declarations, a second time in the copy constructor.

Alternative approaches seem to implement T T.dup() or T 
T.clone(). Apparently, one has to pick one of these equally good 
approaches, and stick with it throughout a codebase. It seems 
good to implement it only for the classes that need it, to 
minimize boilerplate.

Is that the state of the art?

-- Simon


More information about the Digitalmars-d-learn mailing list