[英]Return string vs Passing string by reference to update the value
以下兩個函數中的什么是好的編程實踐:
這個:
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:可以使用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.