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("");
You can't change std::string& getSomeValue(std::string& str) into std::string getSomeValue(). That would break the API and ABI. Existing code using that function would need to be changed.
So one benefit is maintaining API/ABI compatibility. As to why this was written this way, it's probably pre-C++11 code.
However, an overload could be introduced, keeping the old function and introducing the new, better form. The old one can then be marked deprecated:
[[deprecated("unsafe, use getSomeValue() without argument instead")]]
std::string& getSomeValue(std::string& str);
Use of the old function will then generate a compiler warning and the code can be changed over time to adopt the new function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With