繁体   English   中英

返回字符串vs通过引用传递字符串以更新值

[英]Return string vs Passing string by reference to update the value

以下两个函数中的什么是好的编程实践:

  1. 这个:

     std::string buildvalue(const std::string &in) { std::string out; out = // Do some calulation bases on input return out; } 
  2. 或这个:

     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:可以使用std :: string_view代替const std :: string&。 在以下情况下,创建临时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

暂无
暂无

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

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