mercredi 4 mars 2020

Why would you simultaneously return from a function and assign to an argument?

In a codebase I'm working on I keep encountering code like this:

std::string& getSomeValue(std::string& str)
{
    str = "Hello World!";
    return str;
} 

Is there any benefit to writing this over:

std::string getSomeValue()
{
    return "Hello World!";
} 

I appreciate that there is no string construction in the function, but the many disadvantages outway that small benefit. Especially since elision and moving should remove most of the overhead.

It leads to undefined behaviour if called as

std::string s = getSomeValue(s);

It's untidy to write the following, and s now can't be const:

std::string s; 
getSomeValue(s);

You can't pass a temporary, e.g.

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

Aucun commentaire:

Enregistrer un commentaire