Is it ok to use lambda just locally?

  • A+
Category:Languages

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?

 


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..)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: