此链表的分配运算符是否进行深度复制? ///我的列表中有一个名为node * head的属性;
data
答案 0 :(得分:0)
您所显示的不是正确实现的赋值运算符,甚至没有关闭。您的逻辑是倒退,您需要用this
的副本填充another_list
,而不是像您想做的那样相反。
它应该看起来更像这样:
MyList<type>& operator=(const MyList<type> &another_list)
{
if (&another_list != this)
{
node<type> *cur = head;
node<type> *next;
head = NULL;
while (cur != NULL)
{
next = cur->next;
delete cur;
cur = next;
}
node<type>** newNode = &head;
cur = another_list.head;
while (cur != NULL)
{
*newNode = new node<type>();
(*newNode)->data = cur->data;
(*newNode)->next = NULL;
newNode = &((*newNode)->next);
cur = cur->next;
}
}
return *this;
}
或者更好,使用copy-swap idiom:
// default constructor
MyList()
: head(NULL)
{
}
// copy constructor
MyList(const MyList<type> &another_list)
: head(NULL)
{
node<type> *cur = another_list.head;
node<type>** newNode = &head;
while (cur != NULL)
{
*newNode = new node<type>();
(*newNode)->data = cur->data;
(*newNode)->next = NULL;
newNode = &((*newNode)->next);
cur = cur->next;
}
}
// move constructor, C++11 and later only...
MyList(MyList<type> &&another_list)
: head(another_list.head)
{
another_list.head = NULL;
}
// destructor
~MyList()
{
node<type> *cur = head;
node<type> *next;
while (cur != NULL)
{
next = cur->next;
delete cur;
cur = next;
}
}
// copy assignment operator
MyList<type>& operator=(const MyList<type> &another_list)
{
if (&another_list != this)
{
MyList<type> temp(another_list);
std::swap(temp.head, head);
}
return *this;
}
// move assignment operator, C++11 and later only...
MyList<type>& operator=(MyList<type> &&another_list)
{
MyList<type> temp(std::move(another_list));
std::swap(temp.head, head);
return *this;
}
如果不需要支持C ++ 11之前的编译器,则可以合并复制赋值并将赋值运算符一起移动到单个运算符中,该运算符的智能程度足以调用复制构造函数或移动构造函数,具体取决于是否分配左值或右值:
// copy+move assignment operator
MyList<type>& operator=(MyList<type> another_list) // <-- pass by value!
{
MyList<type> temp(std::move(another_list));
std::swap(temp.head, head);
return *this;
}