Consider the following:
unique_ptr<int> foo = make_unique<int>(42);
auto lambda = [bar = move(foo)]()
{
/* Do something with bar */
};
lambda(); // No issues invoking this
cout << "*foo = " << *foo; //Attempts to dereference foo will segfault
Capturing things like a unique_ptr requires use of std::move, so as to maintain the uniqueness of unique_ptr. But what to do when I want to use that same smart pointer after the lambda is destructed? Using foo will give a segfault, and bar is out of scope by that point.
Perhaps unorthodox use of lambda aside, how do I get my unique_ptr back? Is it trapped in the lambda forever?
This can be solved by capturing by reference.
auto lambda = [&]()
{
/* Do something with foo */
};
// or
auto lambda = [&foo]()
{
/* Do something with foo */
};
Allows you to use foo
, without actually moving it.
The only caveat with this is it is up to you to ensure the lifetime of the lambda does not exceed that of the pointer. If it can/does, then you should consider a shared ownership method like using a std::shared_ptr
instead.