What is Return Value Optimization(RVO) ?

What is Return Value Optimization(RVO) ?

Run the following example in any C++ environment of your choice, What would be output that you're expecting ?

#include<iostream>
struct Box {
  Box() = default;
  Box(const Box&) { 
      std::cout << "Copy Constructor being called \n"; 
    }
};

Box func() {
  return Box(); //Line 1
}

int main() {
  std::cout << "Main function entered\n";
  Box obj = func(); // Line2
}

I will say, what i thought about this code before I learnt about RVO,

  • Line 1, An object of Box is being constructed inside func, which is then returned, thus creating a copy
  • Line 2, In main function, object returned by func is copied to local object, creating another copy

I was expecting the copy constructor to be invoked atleast twice. I should admit, i was confused when i ran the code and didn't see a single invocation of copy constructor, Enter the world of Return value optimization. This is the principle behind eliminating these redundant copies

Check it for yourself, by running the code in your compiler
See you in another nugget, Have a great day