【问题标题】:Why non-mutable lambda captures can be moved?为什么可以移动非可变 lambda 捕获?
【发布时间】:2018-05-26 07:02:48
【问题描述】:

AFAIK 非可变 lambdas 将变量捕获为 const。这让我很奇怪,为什么它们还能被移动?

auto p = std::make_unique<int>(0);
auto f = [p = std::move(p)](){ p->reset(); }; // Error, p is const
auto f2 = std::move(f); // OK, the pointer stored inside lambda is moved

【问题讨论】:

    标签: c++ lambda c++14 move-semantics


    【解决方案1】:

    AFAIK 非可变 lambdas 将变量捕获为 const。

    不,他们没有。他们的operator() 重载是const。实际的成员变量不是。

    这和以下没有什么不同:

    class A
    {
      unique_ptr<int> p
    public:
      //Insert constructors here.
    
      void operator() const {p->reset();}
    };
    

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 2020-11-17
      • 2021-11-12
      • 2014-03-24
      相关资源
      最近更新 更多