When moving a unique_ptr into a lambda, why is it not possible to call reset?
- Why does this happen?
Because the function-call operator of a lambda,
Unless the keyword
mutable
was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside thisoperator()
.
and
- Is it possible to capture the
std::unique_ptr
in another way which allows to callreset()
within the lambda
You need to mark it mutable
.
mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions
e.g.
auto l = [v = std::move(u)]() mutable {
v.reset();
};
- Why does this happen?
Because lambdas are by default non-mutable. Therefore all captured objects are const. reset
is a non-const member function that modifies the unique pointer.
- Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda (with C++17 or later)?
Yes. Declare the lambda mutable:
[captures](arguments) mutable { body }
^^^^^^^
This is possible since C++11 where lambdas were introduced. All captured non-const objects of a mutable lambda are non-const copies.