Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why non-mutable lambda captures can be moved?

AFAIK non-mutable lambdas capture variables as const. This makes me wonder why can they still be moved?

auto p = std::make_unique<int>(0);
auto f = [p = std::move(p)](){ p->reset(); }; // Error, p is const
auto f2 = std::move(f); // OK, the pointer stored inside lambda is moved
like image 571
lizarisk Avatar asked Dec 12 '17 14:12

lizarisk


1 Answers

AFAIK non-mutable lambdas capture variables as const.

No, they do not. Their operator() overloads are const. The actual member variables aren't.

It's no different from:

class A
{
  unique_ptr<int> p
public:
  //Insert constructors here.

  void operator() const {p->reset();}
};
like image 134
Nicol Bolas Avatar answered Nov 12 '22 12:11

Nicol Bolas