Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to use lambda just locally? [closed]

Is it alright to define a lambda function to be used only locally, that is in the current block (function/method)? Consider the situation when some code is going to be executed several times (so it'd be logical to put it into a function) but it will never be used outside the block.

void foo() {
    auto bar = []() {
        // some code applicable only inside foo()
    };

    bar();
    bar();
    bar();
}

What are the advantages and disadvantages of this approach, comparing to having bar() declared as normal function?

like image 749
Martin Heralecký Avatar asked Jun 06 '18 09:06

Martin Heralecký


3 Answers

If the option to do so is available then yes, do localise the lambda bar to the particular function.

In C++, we always try to keep objects as local as possible. (Makes code easier to follow, simplifies documentation, facilitates refactoring, &c. &c..)

like image 200
Bathsheba Avatar answered Sep 22 '22 18:09

Bathsheba


I agree that this is good practice. High level logic is almost always easier to read than low level logic. I often write functions in this way:

void foo()
{
  // introduce actors here
  auto something = make_something();

  // introduce detailed definitions
  auto bing = [&]()->bool { ... };  // define what binging means

  auto bong = [&]() { ... };  // define what bonging means

  // perform logic
  while (bing())
    bong();
}

Remember that as of c++17, lambdas are constexpr by default. gcc et. al. often optimise them away completely. None of this is a performance consideration.

like image 21
Richard Hodges Avatar answered Sep 23 '22 18:09

Richard Hodges


You can do it. Main question is will it be more readable? Putting it outside keeps one less level of indentation.

Questions you should ask:

  1. Is bar short function?
  2. Is it pure function, or modifies something?
  3. Is it tightly related to foo, or can be reused elsewhere?
  4. Do you want another level of indentation?
like image 21
dimm Avatar answered Sep 21 '22 18:09

dimm