Search code examples
c++lambdac++14generic-lambda

What's type deduced by auto in lambda expression used to modify a vector of type bool (special container)


I want to change the state of one variable in std::vector<bool> using a function by reference but this doesn't work because std::vector<bool> is a proxy object. However when I try to change it using lambda expression I could modify it. Here's an example:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char **argv)
{
    vector<bool> v(10, true);

    auto modify_bool = [](auto b){ b = false; };

    modify_bool(v[1]);

    for(bool b:v)
        cout << b << endl;

    return 0;
}

I can see that v[1] has been changed to false. My question is what is the type deduced by auto of modify_bool and b?


Solution

  • Calling std::vector<T>::operator[] on a non-const vector object returns a std::vector<T>::reference, which in most cases is T&.

    However, in the case of std::vector<bool>, its internal storage may be optimized to store multiple bools as bits in a single byte, instead of using a normal bool[] array, in which case reference cannot be a normal bool&. It is instead a proxy object that has operator= and operator bool() implemented to assign/read a specific bool element in the vector's internal representation.

    The type of that proxy is unspecified and implementation-specific, but auto can still deduce it.