Search code examples
c++referencervalue-reference

Reference to function return value


Take this example:

#include <string> 

std::string Foo() {
  return "something";
}

std::string Bar() {
  std::string str = "something";
  return str;
}

I don't want to copy the return value, what is better between these two options? And why?

 int main() {
   const std::string& a = Foo();
   std::string&& b = Foo(); 
   // ... 
 }

If I use Bar function now (instead of Foo), are there some difference between main() written above?

 int main() {
   const std::string& a = Bar();
   std::string&& b = Bar(); 
   // ... 
 }

Solution

  • what is better between these two options?

    Neither. This is an exercise in premature optimization. You are trying to do the compilers job for it. Return value optimization and copy elision is practically law now. And move-semantics (applicable for a type like std::string) already provide truly efficient fallbacks.

    So let the compiler do its thing, and prefer value semantics:

    auto c = Foo();
    auto d = Bar();
    

    As for Bar vs Foo. Use whichever you prefer. Bar in particular is RVO friendly. So both will very likely end up being the same.