0

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.

Milan
  • 1,743
  • 2
  • 13
  • 36
  • 2
    C++ made a boo-boo for specializing `std::vector` by packing it to save space. Unfortunately, that means it behaves a little different than other `std::vector`. I think it was a mistake, and they should have made `std::vector_bool` to be the packed one, and `std::vector` to be just like any other... but that ship has sailed. – Eljay Jun 25 '21 at 18:11
  • @Eljay thank you so much for clarifying. I was so confused! 110% agree on having `std::vector_bool` as well as `std::vector` – Milan Jun 25 '21 at 18:35

0 Answers0