Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure default capture overhead

Tags:

c++

lambda

c++14

Is there any overhead in using a default capture mode?

{
   Foo foo = ...;
   Bar bar = ...;
   [&]()
   {
       write(foo);
   }
}

{
   Foo foo = ...;
   Bar bar = ...;
   [&foo]()
   {
       write(foo);
   }
}

To clarify is there any cost in using the former related to bar being capture even if not used?

like image 658
José Avatar asked Oct 30 '15 12:10

José


1 Answers

It is unspecified how the lambda deals with entities captured by reference, from the draft C++14 standard(N4140) section 5.1.2 [expr.prim.lambda]:

An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy. It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference. A member of an anonymous union shall not be captured by reference

This wording was purposely left open to allow implementations to optimize around this, see defect report 750: Implementation constraints on reference-only closure objects which references N2927 which says:

The new wording no longer specifies any rewrite or closure members for "by reference" capture. Uses of entities captured "by reference" affect the original entities, and the mechanism to achieve this is left entirely to the implementation.

like image 63
Shafik Yaghmour Avatar answered Oct 06 '22 01:10

Shafik Yaghmour