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;
unsignedint 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
}
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
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().