0

I found this c++ code but I can't understand this syntax:

auto path_dbus = [&](DBus::Connection &bus) {
    ...
};
Roberto Bonvallet
  • 27,307
  • 5
  • 37
  • 57
developer
  • 4,188
  • 5
  • 33
  • 50

1 Answers1

3

It is a lambda function that:

  • captures any used variables by reference [&]
  • takes an argument (DBus::Connection&)
  • does some work {...}

To break down that line:

auto path_dbus = [&]      (DBus::Connection &bus) {... };
                 ^capture ^arguments              ^work
Cory Kramer
  • 98,167
  • 13
  • 130
  • 181
  • "everything currently in scope" is misleading. Only those used are captured. (§5.1.2[expr.prim.lambda]/11) – RJFalconer Jun 01 '15 at 15:17
  • @RJFalconer Isn't that an implementation detail? – eush77 Jun 01 '15 at 15:19
  • @eush77 there's a [nicely-written explanation here](https://msdn.microsoft.com/en-us/library/dd293603.aspx), scroll to "Capture clause" (specifically "`A common misconception about capture-default is that all variables in the scope are captured whether they are used in the lambda or not`") – RJFalconer Jun 01 '15 at 15:54
  • 1
    @RJFalconer Sorry, could you elaborate a bit more? This behavior is defined in §5.1.2 and hence is technically not an implementation detail (and my original comment is wrong) but as a user of the language I can't tell whether all variables are captured or only those used, can I? Your link doesn't explain why this misconception is worth worrying about. – eush77 Jun 01 '15 at 16:48