How to implement a copy
Paul D. Anderson
paul.d.removethis.anderson at comcast.andthis.net
Thu Mar 18 09:43:58 PDT 2010
If I'm implementing a struct and want to provide for duplication, is there a standard way to implement this?
Here's an example:
//-------------------------------
struct S {
// members of the struct -- three integer values
int a;
int b;
int c;
// here's a copy constructor
this(S s) {
this.a = s.a;
this.b = s.b;
this.c = s.c;
}
// here's the dup property
S dup() {
S s;
result.a = this.a;
result.b = this.b;
result.c = this.c;
return s;
}
// here's opAssign for S
void opAssign(S s) {
this.a = s.a;
this.b = s.b;
this.c = s.c;
}
} // end struct S
// and here's a copy function
S copy(S s) {
S t;
t.a = s.a;
t.b = s.b;
t.c = s.c;
return t;
}
//-------------------------------
Which of these three calls is "better" (more efficient, more intuitive, more consistent...)?
S s; // the original struct
S t = s.dup; // copied via dup
S u = S(s); // copied via copy constructor
S v = s; // copied via opAssign
S w = copy(s); // copied via copy function
Or is this a distinction without a difference?
Paul
More information about the Digitalmars-d-learn
mailing list