问题
Reading up on lambdas, I tried understanding them capturing this and *this. I wrote a small test:
#include <iostream>
#include <functional>
using namespace std;
struct A {
int x = 0;
function<int(void)> get_x_cpy = [=, this]() { return x++; };
function<int(void)> get_x_ref = [&, this]() { return x++; };
};
int main() {
A a;
cout << a.get_x_cpy() << a.get_x_cpy() << a.get_x_ref() << a.get_x_ref() << '\n';
}
and, expecting the get_x_cpy() to make a copy of a I expected to see 0001 or 0101 (depending on when a is copied) but instead it prints 0123, so even the copy-capturing lambda modifies a. I assume this is because the pointer to a is copied, not a itself, so there is still only 1 instance of A in memory. Thus, I tried capturing *this instead of this:
function<int(void)> get_x_cpy = [=, *this]() mutable { return x++; };
function<int(void)> get_x_ref = [&, *this]() mutable { return x++; };
and now the program crashes. Something is going on behind the curtains that I don't understand.
My conjecture is that a copy of a for the first lambda is made upon declaration of a but, for some reason, this copy is immedeatly destructed so any later access crashes the program.
So, the questions are:
- is my conjecture true?
- what is the proper way of capturing the calling object by copy (without incurring the crash)?
- when successfully capturing
*thisby copy, when is the copy made? (I suppose it's when I declare the lambda, so I should see0101in the output, if I am not mistaken...)
EDIT: thanks for the comments regarding mutable!
来源:https://stackoverflow.com/questions/65380474/copy-capturing-this-with-c-lambdas