copy-capturing this with C++ lambdas

China☆狼群 提交于 2020-12-27 07:12:32

问题


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:

  1. is my conjecture true?
  2. what is the proper way of capturing the calling object by copy (without incurring the crash)?
  3. when successfully capturing *this by copy, when is the copy made? (I suppose it's when I declare the lambda, so I should see 0101 in 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!