c++ - How is a lambda moved? -


i don't understand how lambda moved. consider following code:

#include <iostream> #include <utility> #include <string>  struct foo // non-copyable type {     foo() = default;     foo(const foo&) = delete; // cannot copy     foo(foo&&) = default; // can move };  auto lambda = [p = foo()](){     std::string x{"lambda"};      std::cout << x << std::endl; }; // auto copied_lambda = lambda; // cannot copy due foo non-copyable init capture auto moved_lambda = std::move(lambda); // moved  struct functor // "simulate" lambda {     std::string x{"functor"};     void operator()() const     {         std::cout << x << std::endl;     } };  functor functor; // initial functor object auto moved_functor = std::move(functor); // moved  int main() {     lambda(); // why display "lambda" since moved?     moved_lambda(); // displays "lambda", moved in, ok      functor(); // doesn't display "functor", moved     moved_functor(); // displays "functor", moved in, ok } 

as can see, declare foo non-copyable class (but movable) pass init capture of lambda, lambda ends being move-only. lambda closure declares std::string (which movable). next move lambda moved_lambda, expect std::string moved well. however, when invoke lambda() in main(), still displays old string, if wasn't moved @ all.

i "simulated" lambdas functors, , when moving functor moved_functor, initial string in functor moved well, when try displaying in main() null string. puzzled behaviour, why inconsistency? have expected moved lambda (which internally function object) move components , not copy them. explanation local variables inside lambda const, instead of moving them copy them, i'm not sure. case?

your functor not line lambda. lambda looks like:

struct functor // "simulate" lambda {     void operator()() const     {         std::string x{"functor"};         std::cout << x << std::endl;     } }; 

hopefully helps make clear why moved-from lambda still prints "lambda": functor had x moved-from, lambda did not.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -