DEV Community

Gapry
Gapry

Posted on • Edited on

1

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay