lundi 27 avril 2020

Why is a captured variable in C++11 of different value inside a capture?

I am not sure how to explain this behaviour, displayed here with a minimal example. Why isn't size correctly captured ?

#include <iostream>
#include <vector>
using namespace std;


auto&& matcher1KO = [] (vector<int> &v){ 
    int size = v.size();
    cout << "size outside : " << size << "\n";  // print 1
    return [&] (bool b) {
      cout << "v.size() : " << v.size() << "\n"; // print 1
      cout << "size inside : " << size << "\n"; // print 0
    };
};

auto&& matcher2OK = [] (vector<int> &v){ 
    int size = v.size();
    cout << "size outside : " << size << "\n"; // print 1
    return [&] () {
      cout << "v.size() : " << v.size() << "\n"; // print 1
      cout << "size inside : " << size << "\n"; // print 1
    };
};

int main() {
  vector<int> v {+1};

  auto matcherf1 = matcher1KO(v); // 
  matcherf1(true);

  auto matcherf2 = matcher2OK(v);
  matcherf2();
}

Aucun commentaire:

Enregistrer un commentaire