【发布时间】:2021-12-26 05:41:11
【问题描述】:
我的链表实现存在问题,我正在尝试创建一个复制构造函数。
// Copy Constructor
List342(const List342& source)
{
*this = source;
}
List342& operator=(const List342& source)
{
Node<T>* s_node = nullptr; // Source node
Node<T>* d_node = nullptr; // Destination node
if (this == &source)
{
return *this;
}
// Empty memory on destination
DeleteList();
// If the source is empty, return the current object.
if (source.head_ == nullptr)
{
return *this;
}
// Copy source node to destination node, then make destination node the head.
d_node = new Node<T>;
d_node->data = (source.head_)->data;
head_ = d_node;
s_node = (source.head_)->next;
// Loop and copy the nodes from source
while (s_node != nullptr)
{
d_node->next = new Node<T>;
d_node = d_node-> next;
d_node->data = s_node->data;
s_node = s_node->next;
}
return *this;
}
出于某种原因,VS Studio 在d_node->data = s_node->data 行上向我抛出了读取访问冲突,尽管while 循环试图阻止这种情况发生。
罪魁祸首可能在于DeleteList,但由于某种原因,我的其他方法(例如打印链表)在调用DeleteList 后没有任何问题,因为它什么也没打印。我只是想知道这个DeleteList 方法是否有任何缺陷。
// Delete all elements in the linked list
// Not only do you need to delete your nodes,
// But because the Node data is a pointer, this must be deleted too
void DeleteList()
{
// Similar to the linkedlist stack pop method except you're running a while
// loop until you the is empty.
Node<T>* temp;
while (head_ != nullptr)
{
temp = head_;
head_ = head_->next;
// For some reason if I try to delete temp->data, I keep getting symbols not loaded or debug
// assertion errors
// delete temp->data;
// What I can do here is set it to null
// Then delete it. This may have to do how uninitialized variables have random memory assigned
temp->data = nullptr;
delete temp->data;
delete temp;
}
}
这是Node 的定义:
template <class T>
struct Node
{
T* data;
//string* data;
Node* next;
}
【问题讨论】:
标签: c++ pointers linked-list