簡體   English   中英

在 C++ 中,將空字符串作為 function 參數傳遞的更好方法是什么?

[英]which is the better way to pass an empty string as function parameter in C++?

我有三種方法將空字符串作為 function 參數傳遞,如下所示。


void funciton(const std::string& str)
{
}

int main()
{
    //the first way is passing  ""
    funciton("");
    //the sencond way is passing  {}
    funciton({});
    //the third way is passing std::string()
    function(std::string());
    return 0;
}

我看到很多討論建議在返回空字符串時使用 {},我想知道哪種方法更好地傳遞空字符串。

生成的 output 在所有三種情況下都是相同的,最好的是在代碼中清楚地顯示您的意圖的那個,我會 go 和f("") 現在 std::string 支持移動語義,所以如果你主要將它們作為右值傳遞,我不會使用 const 引用。 還要考慮這個:

f(std::string s ="");
f();

並且因為您使用的是 const 引用,所以還要檢查std::string_view在您的用例中是否有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM