为什么移动(&&)而不是const&?

时间:2016-05-09 16:44:54

标签: c++ c++11 visual-c++ c++14

这些是Same函数的定义,但第一个是使用move(&&)传递参数,第二个是使用(const &)传递的。

template<typename T, class Allocator>
void MyList<T, Allocator>::push_front(T && t)
{
    Link<T>* newnode = new Link<T>(t);

    if (empty()) {
        head = std::move(newnode);
        tail = std::move(newnode);
        std::cout << "Linked List Created using move with value: " <<t<< std::endl;
    }
    else {
        head->prev = std::move(newnode);
        newnode->next = std::move(head);
        head = std::move(newnode);
        std::cout << "Node Inserted using move at the beginning of List with value: " <<t<< std::endl;
    }
}

template<typename T, class Allocator>
void MyList<T, Allocator>::push_front(const T & t)
{   Link<T>* newnode = new Link<T>(t);
    if (empty()) {
        head = newnode;
        tail = newnode;
        std::cout << "Linked List Created with value: "  <<t<< std::endl;
    }
    else {
        head->prev = newnode;
        newnode->next = head;
        head = newnode;
        std::cout << "Node Inserted at the beginning of List with value: " <<t<< std::endl;
    }
}

当我在main中运行以下代码时:

 MyList<int> l1;
    l1.push_front(5);
    l1.push_front(std::move(8));

我总是得到cout函数的moveconst &不应该是默认的吗?

1 个答案:

答案 0 :(得分:1)

5本身就是一个右值。它是一个仅用于push_front的临时值,因此编译器可以安全地进行&&调用。要查看预期的行为,请尝试左值:

 MyList<int> l1;
 int foo = 5;
 l1.push_front(foo);
 l1.push_front(std::move(foo));

编译器无法确定您在第一次通话后未能使用foo,因此必须致电const &

相关问题