对于复制赋值运算符,可以使用 copy-and-swap idiom .
例如,在您的情况下,您可以将其添加到 IntList 类定义中(给定您的复制构造函数的代码,我假设您的唯一数据成员是 IntNode* first; ):
// --- swap non-member function ---
friend void swap(IntList& a, IntList& b) /* no-fail */ {
// swap data members one by one
std::swap(a.first, b.first);
}
// --- (copy) assignment operator ---
IntList& operator=(const IntList& other) {
IntList temp(other); // copy construction
swap(*this, temp); // swap
return *this;
// destruction of temp ("old *this")
}
实际上,这可能是更好的风格:
// --- swap non-member function ---
friend void swap(IntList& a, IntList& b) /* no-fail */ {
using std::swap; // enable ADL
// swap data members one by one
swap(a.first, b.first);
}
// --- (copy) assignment operator ---
IntList& operator=(IntList other) { // note: take by value
swap(*this, other);
return *this;
}
/* no-fail */ 注释可以在C 98/03中的 throw() (或者仅仅是 /* throw() */ 注释)中替换,在C 11中为 noexcept .
(注意:不要忘记预先包含std::swap的正确 Headers ,即C 98/03中的 ,C 11中的 (您也可以包括两者) . )
备注:这里 swap 函数在类体中定义,但它仍然是非成员函数,因为它是 friend .
查看整个故事的链接帖子 .
(当然,除了复制构造函数之外,还必须提供正确的析构函数定义(请参阅What is The Rule of Three?) . )