c++ - 将项目添加到链接列表中,通过引用或值传递?

标签 c++

我的部分家庭作业是实现通用链表。 到目前为止我写了这个函数:


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/

相关文章:

c++ - boost::heap::priority_queue 与 std::priority_queue 的比较器

c++ - C++设计策略中的 vector 和

c++ - FMOD_CHANNEL_FREE 未定义,fmod 版本不同?

c++ - 使用::std::vector 创建数组

c++ - 我可以将 "force"线程唤醒吗?

c++ - 在没有窗口的情况下运行 C++ 非托管控制台应用程序(不是批处理文件)

c++ - 由同一模板函数的局部静态变量参数化的模板类型是否应该比较相等?

c++ - GCC 中的结构成员对齐

C++ 条件字符串[i]

c++ - 使用错误版本编译的 OpenGL