简体   繁体   中英

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(); 
   // ... 
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM