我想實現一個類的拷貝構造函數和賦值操作符。我對複製交換習語有些困惑。特別是當涉及到複製構造函數時。拷貝交換習語與拷貝構造函數有什麼關係?我如何避免代碼重複?如何實現拷貝交換成語的複製構造函數
這裏是我的類
頁眉:
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;
}
我這個指南:What is the copy-and-swap idiom?
什麼是'Record :: Actor'? 「Record ::' – StoryTeller
沒有其他限定條件這是一個錯字。 – marsh
除了將'Swap'聲明爲非靜態成員函數(而不是朋友函數或至少一個靜態成員函數)之外,這個習語似乎正確應用。你寫了副本和交換,並獲得了免費的任務(請注意,通過按值接收其參數來隱式調用複製構造函數)。另一個提示:調用它'swap'而不是'Swap'並使用'使用std :: swap; swap(x,y);'而不是'std :: swap(x,y)'啓用ADL,這對自定義類型很有用。 –