How to implement a copy
Pelle Månsson
pelle.mansson at gmail.com
Fri Mar 19 05:18:28 PDT 2010
On 03/18/2010 05:43 PM, Paul D. Anderson wrote:
> 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
>
>
>
>
this(this) is the copy constructor, I think.
Try using that :)
More information about the Digitalmars-d-learn
mailing list