1 year ago

#357225

test-img

John

Lambda factor copyable or moveable

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;
}

c++

c++11

lambda

copy-constructor

move-constructor

0 Answers

Your Answer

Accepted video resources