简体   繁体   中英

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

I have three way to pass an empty string as function parameter as below.


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;
}

I have seen that many discussions recommend to ues {} when return a empty string, and I wonder which is the better way to pass an empty string.

The generated output will be the same in all three cases, the best is the one that clearly shows your intent in the code, I would go with f("") . Nowadays std::string supports move semantics, so if you mostly pass them as rvalues, I wouldn't use const references. consider also this:

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

And because you were using const references, check also if std::string_view could be useful in your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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