1

I used to write lambdas like this:

std::vector<....> data;
//here we're populating data

mylambda=[data{std::move(data)}](...){...}

...
std::function<....> myfunction= mylambda;
...
return myFunction

At first, this seemed like an ok solution, but recently I found that, after being called, std::function calls reset function, which re-initializes the parameters of the lambda function. This seems like something that could potentially cause problems (since when reset is called, data variable is already out of context), but so far I haven't had any issues with this.

Is initializing lambda parameters by moving an object which does out of context a good idea?

Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224
  • What is the purpose of the code? What is the actual problem you need to solve? Are you okay with `data` becoming empty (since you *move* the data)? – Some programmer dude Aug 20 '20 at 01:12
  • Also note that you capture by *value* which means (without a move) the `data` for the lambda is a *copy* of the (local?) variable `data`. Even with the move, the lambdas `data` is still by *value* meaning it retains its contents as long as the lambda object is alive. – Some programmer dude Aug 20 '20 at 01:13
  • @Someprogrammerdude isn't `data{std::move(data)}` calling move constructor for data? yes, I'm totally ok with data becoming unavailable, I'm using this construction to push data processing to another thread – Arsen Zahray Aug 20 '20 at 01:15
  • `data{std::move(data)}` what is the purpose of this capture? – artm Aug 20 '20 at 01:16
  • @artm I'm moving data to the function that is going to be processing it in another thread – Arsen Zahray Aug 20 '20 at 01:17
  • Did you try move construction the `std::function`? `std::function<....> myfunction= std::move(mylambda);` – Dmitry Kuzminov Aug 20 '20 at 01:34
  • @DmitryKuzminov yes, I usually move functions instead of copying them – Arsen Zahray Aug 20 '20 at 01:41
  • I tried this both with and without move: `myfunction= std::move(mylambda)`. In both cases compiler requires the class that you move into the lambda to have a copy constructor (why?). But in caseof moving the lambda into the function the copy constructor is never called. – Dmitry Kuzminov Aug 20 '20 at 01:47
  • 1
    Does this answer your question? https://stackoverflow.com/questions/25421346/how-to-create-an-stdfunction-from-a-move-capturing-lambda-expression – Dmitry Kuzminov Aug 20 '20 at 02:14

0 Answers0