0

As far as I know, I have at least the following three ways to declare a function which accept closures:

  1. by copying
  2. by reference
  3. by moving

e.g.

void FooCopyLambda(std::function<void()> f) {
  // ...
  f();
  // ...
}

void FooRefLambda(const std::function<void()> &f) {
  // ...
  f();
  // ...
}

void FooMoveLambda(std::function<void()> &&f) {
  // ...
  f();
  // ...
}

In This question, people discussed how to pass by reference. But here I also want to know, should I pass it by reference? Or maybe I should pass it by value or moving?

What's the proper way to pass lambda as an argument? Why?

Galaxy
  • 1,129
  • 11
  • 27
  • @Nelfeal That question is specific to reference, this one includes by value and by moving besides be reference – Galaxy Nov 04 '18 at 09:06
  • 3
    Lambdas are **not** `std::function`. Pass them by a forwarding reference `T&&`. – Evg Nov 04 '18 at 09:10
  • 1
    @Evg, Would be better if you can give more details – Galaxy Nov 04 '18 at 09:11
  • 3
    @hxpax [passing lambda as argument - by reference or value?](https://stackoverflow.com/questions/42373146/passing-lambda-as-argument-by-reference-or-value) – Nelfeal Nov 04 '18 at 09:14
  • 1
    BTW, you don't "pass by moving", you pass by rvalue reference, which only bind to rvalues (typically temporaries). But `T&&` as argument of a function template is yet another beast, called a forwarding reference as Evg mentionned. – Nelfeal Nov 04 '18 at 09:37

0 Answers0