Copy and swap idiom

Hello,

I had a question regarding the "copy and swap"-idiom which I've encountered when overloading assignment operators. I usually do it another way, "manually" deleting memory, copying over values etc. I guess that is the other way of doing it.. anyways, even though I find the way I currently do it more intuitive, using the "copy and swap"-technique seems a lot easier and less error-prone.

So, when using the copy and swap-technique, do one just std::swap each data member of "this" class with the rhs? Example:


1
2
3
4
5
6
7
8
9
10
11
12
Class Actor
{
public:
    Foo* foo;
    Bar bar;
    double member1;
    bool member2;
    unsigned int member3;

    Actor(const Actor&);
    Actor& operator=(const Actor a);
}

1
2
3
4
5
6
7
8
9
10
    Actor::Actor& operator=(const Actor a) {
swap(this->foo, a.foo);
swap(this->bar, a.bar);
swap(this->member1, a.member1);
swap(this->member2, a.member2);
swap(this->member3,a.member3);

return *this
}
Last edited on
¿why do you have a `swap()' member function?
1
2
3
4
Actor& Actor::operator=(Actor b){
   this->swap(b);
   return *this;
}
some things to notice:
- `b' is passed by not constant copy, as it needs to be modified by swap()
- if you are going to make swap() a member function, use it as a member function. Remember that `this' is already passed as the first argument, so you don't need three arguments
1
2
3
void Actor::Swap(Actor& first, Actor& second);
//equivalent to
void Swap(Actor *this, Actor& first, Actor& second);

- if you say that you are going to return something, then return something.
Sorry, my post was incomplete! I've fixed it now. The swap() member function was just as I copied it from another example, so just ignore that. The swap() function I used inside the overloaded operator= is std::swap().
Anyone know?
Know what?
I wonder if

1
2
3
4
5
6
7
8
9
10

   Actor::Actor& operator=(const Actor a) {
swap(this->foo, a.foo);
swap(this->bar, a.bar);
swap(this->member1, a.member1);
swap(this->member2, a.member2);
swap(this->member3,a.member3);

return *this
}


is a correct overloaded assignment operator for the class Actor, in order to achieve a "deep copy".
is a correct overloaded assignment operator for the class Actor, in order to achieve a "deep copy".
No, swap is not an assignment and swapping a pointer does certainly not involve a deep copy.


[EDIT]
If the deep copy is done in the copy constructor it will at least not crash.
Last edited on
Logically, yes.
Syntactically, no.
Ok thanks, so what would be the correct way of doing it?
And what do you mean by synstastically wrong?
Last edited on
kyrresc, could you please have a look at the accepted answer here:
https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom

I know it is a long post, and also a bit old, but it’s written remarkably well.
Topic archived. No new replies allowed.