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..)
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With