Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange behaviour of boolean lambda in c++

#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??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading