selbolder
selbolder

Reputation: 527

C++ Lambda, how is the capture clause deep inside

When I have a callback function like this:

using MessageCallback =
    std::function<void(const Message &, uint64_t deliveryTag, bool redelivered)>;

I could declare a static callback function inside a class:

static void MessageCB(const AMQP::Message &message,
                      uint64_t deliveryTag,
                      bool redelivered)
{...}

But I'm not able to access any Member variables inside this Callback Function.

When I write a Lambda Function like this:

 auto MessageCB= [&](const AMQP::Message &message,
                      uint64_t deliveryTag,
                      bool redelivered)
 {...}

I could then use any member variables from the context where I declared the lambda.

How is this working? How exactly is the capture clause working?

What is the difference to a static callback function?

Upvotes: 0

Views: 407

Answers (2)

wtom
wtom

Reputation: 575

No, I undestand how to use it, but I want to undestand how a Lamda enables the access to the capure clause. What is the is the equivalent in c++ 03? How could I rewrite a lamda with a static callback function? – selbolder

Look at boost bind

And here

Upvotes: 0

Ralara
Ralara

Reputation: 569

This cpp reference page explains how Lambda expressions are formed, the following is from the captures section (my emphasis):

[&] captures all automatic variables used in the body of the lambda by reference and current object by reference if exists

If you are asking specifically how does the compiler capture variables when declaring them in a Lambda then this is a useful resource. From that page:

When you add a capture list to a lambda the compiler adds appropriate member variables to the lambda-functor class and a constructor for initialising these variables.enter image description here

Upvotes: 3

Related Questions