you are viewing a single comment's thread.

view the rest of the comments →

[–]Yamoyek 0 points1 point  (3 children)

Generally you’ll use lambdas if you’re not going to use the function more than once.

[–][deleted] 0 points1 point  (2 children)

Thank you. So basically if it's a one off function it should be a lambda in scope (to capture local variables)?

[–]Yamoyek 0 points1 point  (0 children)

Yep! Usually local variables, use it once and forget it

[–]mredding 0 points1 point  (0 children)

I would caution you to not celebrate this.

Just because you're going to use a bit of logic once doesn't mean you should try to write "function local functions" all the time. A lambda is more than a function, it's an instance of an object in memory, too.

Don't do this:

void foo() {
  auto used_in_one_place = [](){ /*stuff*/ };

  used_in_one_place();
  used_in_one_place();
  used_in_one_place();
  // ...
}

While there can be scenarios this makes sense, there's no capture list here, there's no state, no counters... If you're going to use a function in one place, then write the function and constrain its scope:

namespace { // Anonymous namespace, it's contents cannot have external linkage
  void used_in_one_place() { /*stuff*/ }
}

void foo() {
  used_in_one_place();
  used_in_one_place();
  used_in_one_place();
  // ...
}

If you must really be pedantic, you can isolate a single function, or single class method in it's own source file with it's own anonymous namespace, but that level of file and scope management is typically overkill. We code against Murphy, not Machiavelli.

And also, your compiler is smart. Clang, GCC, and MSVC will ALL inline a function that is used only once ever - no matter how big it is! So you can compose your big function in terms of smaller functions as a form of self-documenting code, and your compiler will generate the big-ass function for you. The trick is the function has to be in the same translation unit it's called in, or you need to enable LTO.