For a std::vector<bool> v, why does the declaration auto& r = v[0]; fail to compile?
Correct answer
C. operator[] yields a proxy object by value, not a real bool reference
18 views
C. operator[] yields a proxy object by value, not a real bool reference
18 views
std::vector<bool> is a partial specialisation that packs bits, so its operator[] returns a proxy object of unspecified type by value instead of a real bool&. Binding that temporary to a non-const lvalue reference fails, and taking the address of an element is impossible for the same reason. Use a value copy with auto, or prefer std::vector<char> or std::bitset when references or predictable performance matter.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is C? Ask here and get an explanation.