Search code examples
c++anonymous-methods

What's the benefit to creat an anonymous function and then invoke it immediately?


I read code like this in c++:

const auto candidate_path = std::invoke([&]() {
  if (status == ModuleStatus::SUCCESS || status == ModuleStatus::FAILURE) {
    // clear candidate path if the module is finished
    return convertToPath(nullptr, false, planner_data);
  }
  return convertToPath(
    observer.lock()->getPathCandidate(), observer.lock()->isExecutionReady(), planner_data);
});

The code creates an anonymous function and capture everything by reference [&](){} and then it's called by std::invoke(), I'd like to see if there is any benefit doing it?

Thanks.


Solution

  • The variable candidate_path is intended to be const-qualified. The immediately-invoked lambda allows using (multiple) statements to initialize the variable, rather than just a single expression after the =, without sacrificing const.

    In this specific case it would have worked with use of the ternary operator in a single expression as well, but that might be more difficult to read.

    The reason to use std::invoke to invoke the lambda instead of writing [&](){ /*...*/ }() is probably personal preference of the author. Possible reason I see is that it is easier to recognize that the lambda is being invoked. With the direct function call syntax one can easily miss the () at the end.