C ++ lambda. How to grab a pointer?

For example, there is a way:

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

   // Use l ...
}

How should I grab a pointer: by reference or by value? Inside lambda p does not change, its methods are simply used.

+4
source share
3 answers

The fact that this is a pointer does not affect your decision to hold links or values. Since the pointer is small enough and you do not want to write it, you can fix it by value.

I usually use the following rule:

  • if it is larger than the pointer, use the link because copying can be more expensive than dereferencing
  • , ,
  • ( )

, , . , , , .

+5

(, ++, -). , , - , p. , p , . , .

+3

- - , - capturimg by [&] . , , ot " ".

, , ,  . = (, int ) , mutable lambdas.

If, however, your closure is experiencing a local area, the &capture is unsafe, and I would even advise against =- capture explicitly and ensure that all captured pointers have a sufficient lifetime.

For pointers, in particular, changing the pointer is completely different from changing the indicated directions. Capturing a copy of the pointer when you do not change the pointer itself will not cause any problems.

+2
source

Source: https://habr.com/ru/post/1531768/


All Articles