简体   繁体   English

引用函数返回值

[英]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? 如果我现在使用Bar函数(而不是Foo),上面编写的main()之间是否有一些区别?

 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. 移动语义(适用于std::string类的类型)已经提供了真正有效的后备。

So let the compiler do its thing, and prefer value semantics: 因此,让编译器执行其操作,并首选值语义:

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

As for Bar vs Foo . 至于Bar vs Foo Use whichever you prefer. 使用您喜欢的任何一种。 Bar in particular is RVO friendly. Bar尤其是RVO友好的。 So both will very likely end up being the same. 因此,两者最终很有可能会一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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