簡體   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