和&之间的区别是什么?和&&在基于范围的for循环中?

时间:2015-03-28 17:54:47

标签: c++ for-loop reference rvalue-reference

我想知道基于范围的for循环中for (auto& i : v)for (auto&& i : v)之间的区别是什么,如下代码所示:

#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> v = {0, 1, 2, 3, 4, 5};

    std::cout << "Initial values: ";

    for (auto i : v)    // Prints the initial values
        std::cout << i << ' ';
    std::cout << '\n';

    for (auto i : v)    // Doesn't modify v because i is a copy of each value
        std::cout << ++i << ' ';
    std::cout << '\n';

    for (auto& i : v)   // Modifies v because i is a reference
        std::cout << ++i << ' ';
    std::cout << '\n';

    for (auto&& i : v)  // Modifies v because i is a rvalue reference (Am I right?)
        std::cout << ++i << ' ';
    std::cout << '\n';

    for (const auto &i : v) // Wouldn't compile without the /**/ because i is const
        std::cout << /*++*/i << ' ';
    std::cout << '\n';

}

输出:

  

初始值:0 1 2 3 4 5
  1 2 3 4 5 6
  1 2 3 4 5 6
  2 3 4 5 6 7
  2 3 4 5 6 7

似乎在这里做同样的事情,但我想知道此代码中for (auto& i : v)for (auto&& i : v)之间的区别。

1 个答案:

答案 0 :(得分:2)

This answer可能会回答您的问题,最相关的部分如下:

auto         => will copy the element, but a reference is more efficient
auto&        => will only bind to modifiable lvalues
const auto&  => will bind to anything but make it const, giving us const_iterator
const auto&& => will bind to rvalues