参考函数返回值

1 c++ reference rvalue-reference

举个例子:

#include <string> 

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

std::string Bar() {
  std::string str = "something";
  return str;
}
Run Code Online (Sandbox Code Playgroud)

我不想复制返回值,这两个选项之间哪个更好?为什么?

 int main() {
   const std::string& a = Foo();
   std::string&& b = Foo(); 
   // ... 
 }
Run Code Online (Sandbox Code Playgroud)

如果我现在使用Bar函数(而不是Foo),上面写的main()之间是否有一些区别?

 int main() {
   const std::string& a = Bar();
   std::string&& b = Bar(); 
   // ... 
 }
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 6

这两种选择之间有什么好处?

都不是.这是一个过早优化的练习.你正在尝试为它做编译工作.现在,返回值优化和复制省略实际上是法律.移动语义(适用于类似的类型std::string)已经提供了真正有效的回退.

所以让编译器做它的事情,并且更喜欢值语义:

auto c = Foo();
auto d = Bar();
Run Code Online (Sandbox Code Playgroud)

至于BarVS Foo.使用您喜欢的任何一种.Bar特别是RVO友好.所以两者很可能最终都是一样的.