When moving std::unique_ptr
into the lambda, it is not possible to call reset()
on it, because it seems to be const then:
error C2662: void std::unique_ptr<int,std::default_delete<_Ty>>::reset(int *) noexcept': cannot convert 'this' pointer from 'const std::unique_ptr<int,std::default_delete<_Ty>>' to 'std::unique_ptr<int,std::default_delete<_Ty>> &
#include <memory>
int main()
{
auto u = std::unique_ptr<int>();
auto l = [v = std::move(u)]{
v.reset(); // this doesn't compile
};
}
- Why does this happen?
- Is it possible to capture the
std::unique_ptr
in another way which allows callingreset()
within the lambda (with C++17 or later)?
v
automatically reset when the lambda goes out of scope? – Longclothconst
ptr. However, in case the lifetime of the pointer needs to end before the end of the scope (or another pointer should be assigned or the ownership of the managed object should be transferred to another unique_ptr), you need a non-const unique_ptr. – Dental