Lambda 因子可复制或可移动

发布于 2025-01-17 22:01:14 字数 995 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文