VC++ auto specifier assuming reference qualifier for vector<bool>::back

54 views Asked by At

On using auto specifier to create a variable that is initialized with the return value from vector<bool>::back(), the variable is having a reference qualifier.

int main()
{
    bool b = true;
    bool & j = b;
    auto k = j;
    k = false; // k is of int type. So, j and i are unaffected. 

    std::vector< bool > vec = { true };
    auto l = vec.back();
    vec.pop_back();
    l = false;  // I get a debug assertion here.
}

The k variable has bool as it's type, but variable l has the type std::_Vb_reference<std::vector< bool, std::allocator< bool >>::_Alty >

If I use int instead of bool, auto specifier works for vector as well.

Is it a bug in VC++ ? I am using Microsoft Visual C++ 2013.

1

There are 1 answers

0
Marvin Sielenkemper On BEST ANSWER

vector<bool> is a special beast and not really a vector at all. back does not return a reference but a special reference proxy object which allows access to single bits in the vector. Since it is a proxy, it can do some additional things normal references can not do - like checking if the referenced bit is still there. This only happens in a debug build, though (I hope).

Your problem is caused by the fact that the proxy object is copyable and the auto variable happily takes a copy of the reference proxy whereas a proper reference would be stripped by the compiler and the variable would be a copy of the referenced value.