1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. For a std::vector v, why does the declaration auto& r =…

Added 30 Nov -0001

For a std::vector<bool> v, why does the declaration auto& r = v[0]; fail to compile?

  1. The subscript returns an rvalue reference that cannot bind to auto&
  2. A vector of bool has no operator[] because it is not a container
  3. operator[] yields a proxy object by value, not a real bool reference Correct answer
  4. vector of bool packs bits, so its elements are const and cannot bind

Correct answer

C. operator[] yields a proxy object by value, not a real bool reference

18 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs