【问题标题】:Why is the move(&&) called instead of const &?为什么调用 move(&&) 而不是 const &?
【发布时间】:2016-05-09 16:44:53
【问题描述】:

这些是 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));

我总是得到move 函数的coutconst &amp; 不应该是默认的吗?

【问题讨论】:

  • std::move(new Link&lt;T&gt;(t)) wtf 这应该怎么做?其他动作?
  • @Slava 是的,你的权利,我在每个地方都添加了移动,我打算修改它但我忘了。感谢您的提醒!
  • 编程不是靠猜测来工作的,你应该明白自己在做什么,而不是盲目地到处移动
  • 注意std::move不会移动任何东西,它是一个值类别转换
  • 你应该先阅读这个isocpp.org/blog/2012/11/…

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


【解决方案1】:

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

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

编译器无法确定您在第一次调用后不会使用foo,因此必须调用const &amp;

【讨论】:

  • 你的答案不正确,左值第一个函数也会被调用。
猜你喜欢
  • 1970-01-01
  • 2020-09-01
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多