lizarisk
lizarisk

Reputation: 7840

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

Upvotes: 10

Views: 560

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474536

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();}
};

Upvotes: 19

Related Questions