C++:如何从 lambda 中 "un-capture" 不可复制对象(例如 unique_ptr)?
C++: How do I "un-capture" non-copyables (eg. unique_ptr) from a lambda?
考虑以下几点:
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
捕获像unique_ptr这样的东西需要使用std::move,以保持unique_ptr的唯一性。但是当我想在 lambda 被破坏后使用同一个智能指针时该怎么办?使用 foo 会产生段错误,此时 bar 超出范围。
除了 lambda 的非正统使用之外,我该如何取回我的 unique_ptr?它会永远被困在 lambda 中吗?
But what to do when I want to use that same smart pointer after the lambda is destructed?
您使用 std::shared_ptr
并且没有移动您想要重复使用的东西。
auto foo = std::make_shared(42);
auto lambda = [bar=foo]()
{
/* Do something with bar */
};
lambda(); // No issues invoking this
cout << "*foo = " << *foo; // also fine
这个可以通过引用捕获来解决
auto lambda = [&]()
{
/* Do something with foo */
};
// or
auto lambda = [&foo]()
{
/* Do something with foo */
};
允许您使用 foo
,而无需实际移动它。
唯一需要注意的是,您需要确保 lambda 的生命周期不超过指针的生命周期。如果它 can/does,那么您应该考虑使用共享所有权方法,例如使用 std::shared_ptr
。
考虑以下几点:
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
捕获像unique_ptr这样的东西需要使用std::move,以保持unique_ptr的唯一性。但是当我想在 lambda 被破坏后使用同一个智能指针时该怎么办?使用 foo 会产生段错误,此时 bar 超出范围。
除了 lambda 的非正统使用之外,我该如何取回我的 unique_ptr?它会永远被困在 lambda 中吗?
But what to do when I want to use that same smart pointer after the lambda is destructed?
您使用 std::shared_ptr
并且没有移动您想要重复使用的东西。
auto foo = std::make_shared(42);
auto lambda = [bar=foo]()
{
/* Do something with bar */
};
lambda(); // No issues invoking this
cout << "*foo = " << *foo; // also fine
这个可以通过引用捕获来解决
auto lambda = [&]()
{
/* Do something with foo */
};
// or
auto lambda = [&foo]()
{
/* Do something with foo */
};
允许您使用 foo
,而无需实际移动它。
唯一需要注意的是,您需要确保 lambda 的生命周期不超过指针的生命周期。如果它 can/does,那么您应该考虑使用共享所有权方法,例如使用 std::shared_ptr
。