#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 4, m = 3;
auto get = [&]() {
vector<vector<bool>> arr(n, vector<bool>(m, false));
arr[0][0] = true;
return arr[0][0];
};
cout << get() << endl;
}
This code is returning 0
. While return arr[0][0] == true
is returning 1
, Which is expected.
Can someone explain the issue behind this??
Surprise, std::vector<bool>
doesn't behave exactly the same way as any other specialization of std::vector
. std::vector<bool>
packs it's data so that it can store each element as a single bit. As a consequence of this operator[]
returns a reference object that refers to the chuck of memory from the vector that the bit is stored in.
It is this reference that you return out of your function. Since it is a reference to the vector, and the vector is now gone, you have a dangling reference and accessing it has undefined behavior.