I am trying to implement a copy constructor and a assignment operator for a class. I am getting a bit confused with the copy swap idiom. Especially when it comes to the copy constructor. Does the copy swap idiom have anything to do with a copy constructor at all? How do I avoid code duplication?
Here is my class
Header:
Class Actor
{
public:
Foo* foo;
Bar bar;
double member1;
bool member2;
unsigned int member3;
void Swap(Actor& first, Actor& second);
Actor(const Actor&);
Actor& operator=(const Actor);
}
Cpp:
void Actor::Swap(Actor& first, Actor& second)
{
// Swap wont work with my non pointer class
Bar temp = first.bar;
first.bar = second.bar;
second.bar = temp;
std::swap(first.foo, second.foo);
std::swap(first.member2, second.member2);
std::swap(first.member3, second.member3);
}
// What goes here? Is this a correct copy constructor? Does this have anything to do with a copy swap idiom? How can I avoid code duplication in my copy constructor?
Actor::Actor(const Actor& other)
{
foo = new Foo();
*foo = *other.foo;
bar = other.bar;
member1 = other.member1;
member2 = other.member2;
member3 = other.member3;
}
Actor& Actor::operator=(Actor other)
{
Swap(*this, other);
return *this;
}
I am following this guide: What is the copy-and-swap idiom?