Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between & and && in a range-based for loop?

Tags:

I'm wondering what's the difference between for (auto& i : v) and for (auto&& i : v) in a range-based for loop like in this code:

#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';

}

The output:

Initial values: 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

Both seem to do the same thing here but I'd like to know what's the difference between for (auto& i : v) and for (auto&& i : v) in this code.

like image 817
LHLaurini Avatar asked Mar 28 '15 17:03

LHLaurini


1 Answers

This answer will probably answer your question, the most relevant part is the following:

By using auto&& var = you are saying: I will accept any initializer regardless of whether it is an lvalue or rvalue expression and I will preserve its constness.

auto         => will copy the element, but a reference is more efficient
auto&        => will bind to modifiable lvalues
const auto&  => will bind to anything but make it const, giving us const_iterator
const auto&& => will bind to rvalues
like image 134
Beginner Avatar answered Sep 24 '22 03:09

Beginner