gpt4 book ai didi

c++ - 引用函数返回值

转载 作者:行者123 更新时间:2023-11-30 00:44:47 24 4
gpt4 key购买 nike

举个例子:

#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();

至于 BarFoo。使用您喜欢的任何一个。 Bar 特别适合 RVO。所以两者很可能最终是一样的。

关于c++ - 引用函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com