In a long C++ function one common issue when reading the code is that there are often too many variables that potentially could be modified making it harder to keep track of them.
One typical case for me is where a variable is only used when initializing another, e.g, I want to keep a
after this fragment, and "kill" x
(and there are multiple such fragments):
...
extern int bar(int, int&);
int x=5;
const int a=bar(..., x);
// x is no longer used, but a is used
...
Note: I'm using variables of int-type to make the example self-contained, but in many cases they are class-object - with virtual functions, and in particular different classes for different fragments.
Sometimes parts of x
is used after the function call, and sometimes not - but unfortunately it's the same function bar so making it an out-argument isn't straightforward.
The following would be one obvious solution, but then a
is no longer initialized and cannot be const.
...
int a;
{
extern int bar(int, int&);
int x=5;
a=bar(..., x);
}
...
https://stackoverflow.com/a/15153194/5603247 indicates that another solution is to define and directly call a lambda:
...
const int a= [=](){
extern int bar(int, int&);
int x=5;
return bar(..., x);
}();
...
Is this the best way to accomplish this? Are there any downsides?
As far as I can see there is no performance penalty - when optimization is enabled - https://godbolt.org/z/c1qn9M