Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use copy elision when function is called in if block

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

like image 983
pseyfert Avatar asked Dec 06 '22 08:12

pseyfert


2 Answers

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();
like image 63
Ruslan Avatar answered Jan 11 '23 23:01

Ruslan


Immediately-Invoked Lambda Expression (IILE) can save the day in this and more complicated cases:

A a = [&] {
  if (…) {
    return function1();
  } else {
    return function2();
  }
}();
like image 25
Anton3 Avatar answered Jan 12 '23 00:01

Anton3