kaa kaa - 1 year ago 81
C++ Question

C++ lambda. How need to capture the pointer?

For example, there is a method:

void foo( A* p )
auto l = [=](){ /* Do Something using p */ };

// Use l ...

How I should to capture the pointer: by reference or by value?
Inside lambda p is not changed, just used its methods.

Answer Source

The fact that it is a pointer doesn't affect your decision about ref or value capture. Since a pointer is small enough and you don't want to write it, you can capture by value.

I usually use the following rule:

  • if it's bigger than a pointer, use a reference because the copying might be more expensive than the dereference
  • if you want to see changes from outside the lambda, obviously references are the only option
  • otherwise (if it's small and doesn't change) capture by value

So a pointer that doesn't change should be captured by value. If the compiler detects that there are no writes, it might optimize a capture by reference and pass by value anyway, but I'm not sure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download