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.

有帮助吗?

解决方案

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.

其他提示

A pointer does not have methods (or, in C++ terminology, member functions). You probably mean you're only calling member functions of the object pointed to by p. Therefore, if you don't want to affect p itself, there is no need to capture it by reference. So just capture it by value, as you do now.

If you have a truly local lambda -- one whose lifetime does not exceed its scope -- capturimg by [&] is usually harmless. In many situations, the references can be treated as pure aliases by reasonably smart compilers, and it makes ot behave like a 'local function' would.

If there is lots of state in your local scope, describing exactly what you capture is sometimes good. And = on small cheap objects (like int or pointers) with trivial copy can also be treated much like an alias, especially with non mutable lambdas.

If however your closure outlives the local scope, & capture is unsafe, and I would even advise against = -- capture explicitly, and ensure any pointers captured have sufficient lifetime.

For pointers in particular, a modifying the pointer is completely different than modifying the data pointed to. Capturing a copy of the pointer when you do not modify the pointer itself will not cause any problems.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top