提问人:John 提问时间:3/31/2022 最后编辑:Jarod42John 更新时间:3/31/2022 访问量:109
Lambda 因子可复制或可移动
Lambda factor copyable or moveable
问:
lambda 只是一个无名类的实例。如果它没有捕获任何内容,它甚至不会有任何成员变量。
我认为特定的 lambda 是可复制的还是可移动的取决于实际捕获的对象(和变量)是可复制的还是可移动的。
此外,如果特定 lambda 捕获所有对象(或将它们称为变量)作为参考,则此 lambda 因子必须是可移动和可复制的。
但是这个代码片段让我完全困惑(请注意代码片段中的注释):
#include <mutex>
#include <map>
#include <iostream>
constexpr int FOO_NUM = 5;
int main()
{
std::mutex mt_lk;
auto factor1 =[&mt_lk](){{
std::lock_guard<std::mutex> lk(mt_lk);
std::cout << "hello world, first" << std::endl;
}};
auto factor2 = factor1;
auto factor3 = std::move(factor1); //I think the mt_lk is already moved here.
factor2();
factor3();
std::lock_guard<std::mutex> lk(mt_lk); //I think mt_lk could not be called here. But no problem is found now.
std::cout << "hello world, second" << std::endl;
}
答: 暂无答案
评论
std::mutex
既不可移动也不可复制,都得到引用。factor*
mt_lk
std::move(factor1)
mt_lk
ml_lk
factor*
mt_lk
int