DEV Community

Gapry
Gapry

Posted on • Updated on

Introduce C++ Lambda

Introduction

I will show three concepts of C++ Lambda in the blog post.

  • Subroutine
  • Capture by value
  • Capture by reference

Subroutine

We cannot define a routine in any existing routine.

void f(void) {
  int sum(int x, int y) {
    return x + y;
  }
}
Enter fullscreen mode Exit fullscreen mode

So, we need the lambda expression. Let's rewrite the code as following.

void f(void) {
  auto sum = [](int x, int y) -> int {
    return x + y;
  };
}
Enter fullscreen mode Exit fullscreen mode

Capture by value

One of the C++ Lambda features calls Capture, here is the example usage.

void f(void) {
  auto sum = [s = 1](int x, int y) -> int {
    return (x + y) << s;
  };
}
Enter fullscreen mode Exit fullscreen mode

As you can see it likes function parameters, it's the capture by value.

Capture by reference

Typically, we have the call-by-value and call-by-reference in Computer Science. Just like that, we have the capture by value and capture by reference in C++.

void f(void) {
  auto s   = int(1);
  auto sum = [&](int x, int y) -> int {
    return (x + y) << s;
  };
}
Enter fullscreen mode Exit fullscreen mode

The benefit of the capture by reference is that can avoid the coping overhead.

Thank you for reading, see you next time.

Top comments (0)