passing lambda as argument - by reference or value?

后端 未结 2 468
执笔经年
执笔经年 2020-12-15 17:42

I\'ve written a template code that takes a functor as an argument and after some processing, executes it. Although someone else might pass that function a lambda, a function

2条回答
  •  悲&欢浪女
    2020-12-15 18:07

    As a possible drawback, note that passing by copy could not work if the lambda isn't copyable. If you can get away with it, passing by copy is just fine.
    As an example:

    #include
    #include
    
    template
    void g(F &&f) {
        std::forward(f)();
    }
    
    template
    void h(F f) {
        f();
    }
    
    int main() {
        auto lambda = [foo=std::make_unique()](){};
    
        g(lambda);
        //h(lambda);
    }
    

    In the snippet above, lambda isn't copyable because of foo. Its copy constructor is deleted as a consequence of the fact that the copy constructor of a std::unique_ptr is deleted.
    On the other side, F &&f accepts both lvalue and rvalue references being it a forwarding reference, as well as const references.
    In other terms, if you want to reuse the same lambda as an argument more than once, you cannot if your functions get your object by copy and you must move it for it's not copyable (well, actually you can, it's a matter of wrapping it in a lambda that captures the outer one by reference).

提交回复
热议问题