Search code examples
c++c++11lvaluervalue

Return values in c++03 vs 11


I have spend a few hours about rvalue s and lvalue. Here is what I understand

int main()
{
  //.....
  Foo foo = Bar1();
  foo = Bar2();
  //......
}  

Foo Bar1()
{
  //Do something including create foo
  return foo;
}

Foo& Bar2()
{
  //Do something including create foo
  return foo;
}

Under c++03, Bar1() would copy the return object (just before return), and then return the address of the copied object; executing a wasteful copy of an object which is about to be destroyed. Bar2() would return the object created within the function.

Under c++11, Bar1() and Bar2() would essentially be equivalent (and also equivalent to Bar2() of c++03).

Is that right? If not, please elaborate.


Solution

  • The concept of rvalues and lvalues didn't change from older C++ to C++11. What you describe as "C++03" is what should happen. Some compiler optimizations in some cases can reduce the number of unnecessary copies (including unnecessary copy-constructor calls!), but otherwise it is the same.

    What did change is that C++11 introduced a concept of rvalue-reference (T&&).

    There are several articles on it that you can google up, for example over here:

    http://thbecker.net/articles/rvalue_references/section_01.html