In the following snippet, no move and no copy of A
happens thanks to copy elision
struct A;
A function1();
A function2();
int main(int argc, char**) {
if (argc > 3) {
A a = function1();
} else {
A a = function2();
}
return 0;
}
This is nice, however a
is not accessible outside the if-block. When declaring a
outside, then a move happens
struct A;
A function1();
A function2();
int main(int argc, char**) {
A a;
if (argc > 3) {
a = function1();
} else {
a = function2();
}
return 0;
}
What is a recommendable attern to profit from copy elision when it should happen in an if block on the call site into a variable outside the if scope?
Compiler-Exlorer link
In this particular case you can use the ternary conditional:
A a = argc>3 ? function1() : function2();
In more complicated cases you may need to save the condition and do several checks, e.g.
const bool cond = argc>3;
A a = cond ? function1() : function2();
A b = cond ? function3() : function4();
Immediately-Invoked Lambda Expression (IILE) can save the day in this and more complicated cases:
A a = [&] {
if (…) {
return function1();
} else {
return function2();
}
}();
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