0

I was reading this SO question and found that best practice is to return by a value. so I ran below two examples in godbolt with ARM gcc 10.2(linux) compiler to get assembly instructions for both

1.

#include <iostream>
#include <vector>

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

int main()
{
   std::vector<int> && rval_ref = return_vector();
   while(1){}
  return 0;
}
  1. Almost same but without &&
#include <iostream>
#include <vector>

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

int main()
{
   std::vector<int>  rval_ref = return_vector();
   while(1){}
  return 0;
}

now code with rvalue && has more instructions compared to code without rvalue reference. shouldn't they be same ?

Below are extra assembly instructions for code with rvalue reference (left is code with rvalue ref && and right is code without it.)

enter image description here

ART
  • 1,509
  • 3
  • 29
  • 47
  • What optimization options are you using? – Nate Eldredge Jun 02 '21 at 20:41
  • I didn't use any explicit optimisation option. – ART Jun 02 '21 at 20:42
  • 4
    Then that's your problem right there. Without optimization it is very common for a compiler to emit unnecessary code, or to fail to notice that two "obviously" equivalent pieces of code are actually the same. In fact, it looks to me like with `-O2` you do get identical code in `main()` for both versions. – Nate Eldredge Jun 02 '21 at 20:45
  • Yeah you are right about it. Thank you. – ART Jun 02 '21 at 20:49
  • 1
    Would probably be more interesting to look at a case where the callee can't just inline and optimize away, and where you use the result. (e.g. return one element of the vector, like `int foo() { tmp = bar(); return tmp[1]; }`. [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116)). Oh, that's identical, too. https://godbolt.org/z/5bGcnboxh – Peter Cordes Jun 02 '21 at 21:11

0 Answers0