0

As the subject, here is the related code (check https://godbolt.org/z/tDg9yG):

#include <vector>

int main()
{
    std::vector<bool> v(10);
    for (auto& e : v)
        e = true;
}

The compiling error:

<source>:6:16: error: non-const lvalue reference to type 'std::_Bit_reference' cannot bind to a temporary of type 'std::_Bit_iterator::reference' (aka 'std::_Bit_reference')

    for (auto& e : v)

               ^ ~
/opt/compiler-explorer/gcc-9.3.0/lib/gcc/x86_64-linux-gnu/9.3.0/../../../../include/c++/9.3.0/bits/stl_bvector.h:811:7: note: selected 'begin' function with iterator type 'std::vector<bool, type-parameter-0-0>::iterator' (aka 'std::_Bit_iterator')

      begin() _GLIBCXX_NOEXCEPT

Here is the code which compiles: #include #include

int main()
{
    std::vector<int> v(10);
    for (auto& e : v)
        e = 1;

    std::cout << v.front() <<std::endl;
}
John
  • 2,963
  • 11
  • 33
  • @cigien I clearly know auto && could return references of rvalues and lvalues. Does auto & only return a reference of lvalues. Am I right? – John Jun 10 '20 at 03:06
  • `auto&` does not "return" anything. It is an lvalue reference. Period. – Nicol Bolas Jun 10 '20 at 03:08
  • @NicolBolas Could `e` only be the type of lvalue reference in "for (auto& e : v)"? – John Jun 10 '20 at 03:11
  • `e` isn't a type, so it can't be the type of anything. `e` is a variable, and in this case it is an lvalue reference variable. – Nicol Bolas Jun 10 '20 at 03:42
  • @NicolBolas As per the documentation aforementioned, which says that: "its(vector) iterators return a Proxy. And since the returned Proxy is an prvalue (a temporary), it cannot bind to an lvalue reference such as auto&.". One more question raises, **why the returned Proxy is an prvalue?**. And the cppreference (https://en.cppreference.com/w/cpp/container/vector_bool/reference) says that[emphasis mine] : The primary use of std::vector::reference is to **provide an l-value** that can be returned from operator[]. Where goes wrong? I would be grateful to have some with this question. – John Jun 10 '20 at 04:53
  • 1
    The reasons why `vector` is the way it is is an entirely separate question. One which is [answered by the question](https://stackoverflow.com/questions/17794569/why-is-vectorbool-not-a-stl-container) linked from the answer in the duplicate question. – Nicol Bolas Jun 10 '20 at 05:05

0 Answers0