vendredi 25 juin 2021

Using lvalue reference v/s rvalue reference in a non-const way in a range-based for loop [duplicate]

I've been trying to understand the difference between using lvalue reference v/s using rvalue reference in a non-const way a range-based for loop and stumbled upon this: What is the advantage of using forwarding references in range-based for loops?

However, I'm still not 100% clear on when to use which one. Because this

int main() {
    std::vector<bool> vec(5);
    for (auto &elem : vec)
        elem = true;
}

does not compile and gives this error:

main.cpp:7:23: error: cannot bind non-const lvalue reference of type ‘std::_Bit_reference&’ to an rvalue of type ‘std::_Bit_iterator::reference {aka std::_Bit_reference}’
     for (auto &elem : vec)
                       ^~~

So, here I should use rvalue reference (as I guess I don't have any other option, right!?)

But on the other hand, this

int main() {
    std::vector<int> vec(5);
    for (auto &elem : vec)
        elem = 3;
}

gets compiled without any error! Why? I mean why does std::vector<int> get compiled but std::vector<bool> does not?

To me, it looks like rvalue reference works every time but let say for some reasons if I want to use lvalue reference then in which particular situations it will work and in which it won't? Also, why does rvalue reference works every time?

Note: In this question, my focus is only on updating/modifying elements in a range-based for loop, i.e. non-const way. I'm not talking about just accessing/reading them i.e. const way.

Aucun commentaire:

Enregistrer un commentaire