通过引用链接列表进行C ++调用

问题描述

我是C ++学习的新手,它实现了链表,但我不明白为什么我在函数insertAtfront的参数中未按引用调用输出错误吗?为什么参数必须是const引用?

#include <iostream>

template <typename T>
class List {
public:
  const T & operator[](unsigned int data);
  void insertAtFront(const T & data);//&
private:
  class ListNode {
  public:
    const T & data;
    ListNode * next;
    ListNode(const T & data_): data(data_),next(nullptr){} //&
  };
    ListNode * head_=nullptr;
};

template <typename T>
const T & List<T>::operator[](unsigned int index){
  ListNode * through=head_;
  while(index>0  && through->next!=nullptr){
    through = through->next;
    index--;
  }
  return through->data;
}
template <typename T>
void List<T>::insertAtFront(const T & data){ //&
  ListNode * Ptr=new ListNode(data);

  Ptr->next=head_;
  head_=Ptr;
}
int main(){
  List<int> L;
  L.insertAtFront(2);
  L.insertAtFront(55);
  std::cout<<L[0]<<std::endl;
  std::cout<<L[1]<<std::endl;
}

解决方法

您的列表包含输入数据的引用,但不知道何时清除引用。

我将其调整为以下代码: 或在https://godbolt.org/z/7GG5rW

上尝试
#include <iostream>

template <typename T>
class List {
public:
  const T & operator[](unsigned int data);
  void insertAtFront(const T data); // Remove &
private:
  class ListNode {
  public:
    const T data;  // Remove &
    ListNode * next;
    ListNode(const T & data_): data(data_),next(nullptr){} // Remove &
  };
    ListNode * head_=nullptr;
};

template <typename T>
const T & List<T>::operator[](unsigned int index){
  ListNode * through=head_;
  while(index>0  && through->next!=nullptr){
    through = through->next;
    index--;
  }
  return through->data;
}
template <typename T>
void List<T>::insertAtFront(const T & data){ //&
  ListNode * Ptr=new ListNode(data);

  Ptr->next=head_;
  head_=Ptr;
}
int main(){
  List<int> L;
  L.insertAtFront(2);
  L.insertAtFront(55);
  std::cout<<L[0]<<std::endl;
  std::cout<<L[1]<<std::endl;
}

为了进行优化,您可以使用std::moveperfect forwarding来提高性能。