为什么编译器在lambda上使用复制构造函数而不是移动构造函数?

Why does the compiler use the copy constructor on my lambda instead of the move constructor?

本文关键字:构造函数 移动 复制 编译器 lambda 为什么      更新时间:2023-10-16

我试图使用通用捕获语法将unique_ptr移动到lambda,然后将其包装在std::function中。代码很简单:

#include <functional>
#include <memory>
using namespace std;
int main()
{
    unique_ptr<int> x;
    function<void()> y = [x(move(x))]() {};
}

选择了template<typename T> function(T t)构造函数,但是失败了,因为它试图复制lambda。为什么它调用复制构造函数而不是移动构造函数,我能做些什么来解决这个问题?

std::function只能用于CopyConstructible类型,参见LWG 1287对此进行了澄清。

如果你的字体是不可复制的,你不能把它放在std::function