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;
}