以下两个函数中什么是好的编程实践:
这个:
std::string buildvalue(const std::string &in) { std::string out; out = // Do some calulation bases on input return out; }
或者这个:
void buildvalue(const std::string &in, std::string &out) { out = // Do some calulation bases on input }
谨慎使用 2 函数是调用者可能传递非空字符串。有没有什么需要注意的地方。
最佳答案
在第一种情况下,编译器将能够优化返回值。它将返回值放在调用函数中。例如,
std::string foo(...) { ... }
// ...
std::string result = foo(...);
编译器会将 foo 返回值放在结果点上。 它使我们免于引用参数和过早的变量声明。 稍微C++17: 相反,const std::string& 你可以使用 std::string_view。它的优点是在以下情况下创建临时 std::string 是可选的:
void foo(const std::string&);
// ...
foo("hello world"); // here will be create std::string object
使用 std::string_view (c++17)
void foo(std::string_view);
// ...
foo("hello world"); // more productive
+ std::string 有运算符 std::string_view,这导致它到 std::string_view
关于c++ - 返回字符串与通过引用传递字符串以更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287587/