Passing lambda by value or reference simplifies inline?

A similar question was asked earlier, but I'm still confused. I believe that STL only conveys value, because passing by reference can have consequences in a multi-threaded environment. Say when two or more threads execute a mutable lambda. I am currently using a universal link when I just want to call lambda:

template <typename F> inline void invoke(F&& f) { f(); } 

This binds to any function object, like to const& , but maybe this is a bad idea for inline. Is the lambda passed by the copy easier to embed in the compiler? I would like the past lambdas to be as "permeable" as possible.

+7
c ++ lambda c ++ 14
source share
1 answer

Think of lambda as a small object with a function call operator:

 int foo = 1000; auto f = [=]() ->int { return foo; }; 

somewhat equivalent:

 class FooLambda { int foo; public: FooLambda(int foo) : foo(foo) {} int operator()(){ return foo; } }; // ... int foo = 1000; FooLambda f(foo); 

So, you see that the function object itself can be embedded if it is displayed in the same translation unit as it is (and, possibly, if not using compilers more than a compiler). Since your invoke is a template, it knows the actual type of lamdba, and you do not force it to jump over function bypass pointers, which is a big nesting inhibitor.

Taking the called object by value or reference in invoke determines whether the captured variables are local to the function body or not, which may matter if this means that they will be in the cache.

+2
source share

All Articles