我正在创建一个循环链接列表模板类 . 我有一个赋值运算符,一个循环列表到另一个 . 但是,当我使用复制构造函数创建List并将原始列表分配给复制列表时,它会生成分段错误 .

cout<<"cl: "<<cl<<endl;
cout<<endl<<"C
CircularList<int> cl2(cl);
cl=cl2;

我已经使用cout语句对此进行了广泛测试,并隔离了发生错误的行 .

template <class T>
CircularList<T>& CircularList<T>::operator=(const CircularList<T> 
&other)
{
    this->clear();
    if(other.tail==NULL)
    {
        tail=NULL;
        return (*this);
    }
    Node<T> *ptr=other.tail;
    tail= new Node<T>(ptr->element);
    Node<T> *node=tail;
    while(ptr->next!=other.tail)
    {
        ptr=ptr->next;
        //a statement used for testing output
        cout<<ptr->element<<endl;
        node->next=new Node<T>(ptr->element); //segfault
        node=node->next;
    }
    node->next=tail;
    return *(this);
}

复制构造函数:

template <class T>
CircularList<T>::CircularList(const CircularList<T>& other)
{
    if(other.tail==NULL)
    {
        tail=NULL;
        return;
    }

    Node<T> *ptr=other.tail;
    tail= new Node<T>(ptr->element);
    Node<T> *node=tail;
    while(ptr->next!=other.tail)
    {
        ptr=ptr->next;
        node->next=new Node<T>(ptr->element,NULL);
        node=node->next;
    }
    node->next=tail;
}

Node构造函数的代码:

Node(T data, Node<T>* n = 0)
    {
        //cout for testing
        cout<<data<<endl;
        element =data;
        next = n;
    }

运行此代码时,它会在类的int实例上生成以下输出,其中第一个列表的内容为[8,7,6,5,4,11,3,2,1,0]

cl: [8,7,6,5,4,11,3,2,1,0]

Copy constr: 
0
8
7
6
5
4
11
3
2
1
0
8
8
7
7
6
6
5
5
4
4
11
11
3
3
2
2
1
make: *** [makefile:5: run] Segmentation fault (core dumped)

读取的所有数据输出两次,一次在operator =函数内,一次在Node的构造函数内,除了发生分段错误的最后一个 .

代码不会进入Node构造函数块 .

我感谢任何帮助 . 谢谢!

我创建了一个github存储库,其中包含重现错误所需的文件:https://github.com/precious-princess-peach/Circular_linked_list_test