举个例子:
#include <string>
std::string Foo() {
return "something";
}
std::string Bar() {
std::string str = "something";
return str;
}
我不想复制返回值,这两个选项之间哪个更好?为什么?
int main() {
const std::string& a = Foo();
std::string&& b = Foo();
// ...
}
如果我现在使用 Bar 函数(而不是 Foo),与上面写的 main() 有什么区别吗?
int main() {
const std::string& a = Bar();
std::string&& b = Bar();
// ...
}
最佳答案
what is better between these two options?
都没有。这是过早优化的练习。你正试图为它做编译器的工作。返回值优化和复制省略现在实际上是法律。移动语义(适用于像 std::string
这样的类型)已经提供了真正有效的回退。
所以让编译器做它的事情,并且更喜欢值语义:
auto c = Foo();
auto d = Bar();
至于 Bar
与 Foo
。使用您喜欢的任何一个。 Bar
特别适合 RVO。所以两者很可能最终是一样的。
关于c++ - 引用函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951306/