Lambda 因子可复制或可移动
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;
}
A lambda is just an instance of a nameless class. If it doesn't capture anything, it won't even have any member variables.
I think whether a specific lambda is copyable or moveable lies on whether the actually captured objects(and variables) are copyable or moveable.
Furthermore, if a specific lambda captures all the objects(or call them as variables) as reference, then this lambda factor must be moveable and copyable.
But this code snippet makes me totally confused(please pay attention to the comment in the code snippet):
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论