据我所知,不可变的lambda作为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
据我所知,不可变的lambda作为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
据我所知,非可变 lambda 表达式会将变量作为 const 进行捕获。
不是这样的。它们的 operator()
重载是 const
的,但实际的成员变量并不是。
这和以下代码没有什么区别:
class A
{
unique_ptr<int> p
public:
//Insert constructors here.
void operator() const {p->reset();}
};