我的部分家庭作业是实现通用链表。 到目前为止我写了这个函数:
template<class T>
void List<T>::insert(const T& data)
{
List<T>::Node* newNode = new List<T>::Node(data);
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
size++;
}
如您所见,我通过引用获取数据,但我也可以通过值获取数据。 我的问题是哪种方法更好,为什么?
最佳答案
在 C++98/03 中,您所拥有的通常是正确的解决方案。在 C++11 中,你可以保持不变,你的情况不会更糟。但是如果你想提高效率,你可以做一些修改。有两种思想流派。最有效的解决方案需要一点代码重复。您需要两个函数。
template<class T>
void List<T>::insert(const T& data) // take a const reference
{
List<T>::Node* newNode = new List<T>::Node(data); // copy it in
...
template<class T>
void List<T>::insert(T&& data) // take an r-value reference
{
List<T>::Node* newNode
= new List<T>::Node(std::move(data)); // move it in
...
另一种方法在大多数情况下效率稍低,并且避免了代码重复:
template<class T>
void List<T>::insert(T data) // take a value (copy)
{
List<T>::Node* newNode
= new List<T>::Node(std::move(data)); // move it in
...
关于c++ - 将项目添加到链接列表中,通过引用或值传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18884269/