gpt4 book ai didi

c++ - 将 unique_ptr 移入 lambda 时,为什么不能调用 reset?

转载 作者:IT老高 更新时间:2023-10-28 12:35:23 26 4
gpt4 key购买 nike

当将 std::unique_ptr 移动到 lambda 中时,无法在其上调用 reset(),因为它似乎是 const :

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
};
}
  1. 为什么会这样?
  2. 是否有可能以另一种方式捕获 std::unique_ptr 以允许在 lambda 中调用 reset()(使用 C++17 或更高版本)?

最佳答案

  1. Why does this happen?

因为 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 this operator().

  1. Is it possible to capture the std::unique_ptr in another way which allows to call reset() within the lambda

你需要标记它可变

mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions

例如

auto l = [v = std::move(u)]() mutable {
v.reset();
};

关于c++ - 将 unique_ptr 移入 lambda 时,为什么不能调用 reset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com