0

I have the following example to capture a variable in lambda. If I capture it by value, the printed value is 12 which is expected. If I capture it by reference, the printed value is 02. I don't understand why. I wanted to use capture by reference to avoid copy.

class test {
    int i_;
  public:
    test(int i) : i_(i) {}

    void see() const {
        std::cout << i_ << std::endl;
    } 
};

int main ()
{
  std::vector<test> vec;
  vec.emplace_back(1);
  // expected 
  // auto f1 = [op{vec.back()} () { 
  //     op.see()
  // }

  // Not expected
  auto f1 = [op{&vec.back()}]() {
      op->see();
  };
  
  vec.emplace_back(2);
  auto f2 = [op{&vec.back()}]() {
      op->see();
  };
  
  f1();
  f2();
  return 0;
}
Zack
  • 1,205
  • 2
  • 14
  • 38

1 Answers1

5

emplace_back() potentially reallocates, and reallocation of a std::vector invalidates all existing iterators, pointers, and references, including the captured reference.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720