I've been reading up on the benefits of using std::string_view
, and why it should be used in parameter lists. And I understand that returning a string_view
is generally not recommended.
However, say I have a simple function that accepts a string
adds a suffix. I can think of two methods:
std::string AddSuffix(std::string_view inputString)
{
return std::string(inputString) + "!";
}
Or
std::string AddSuffix(std::string inputString)
{
return inputString + "!";
}
If I have to make a copy of the inputString
either way, is there any reason to use one over the other?
The problem of both your variants is that they create 2
std::string
objects, both of which need to allocate memory (in case that those strings are long enough not to fit into the SSO buffer). The cause here is thatoperator+
returns (by value) a newstring
object.If you want to save one allocation, you can modify the
std::string_view
case as follows:In this case, only a single allocation is required when RVO is applied (all major implementations will apply it).
Live demo showing allocations: https://godbolt.org/z/44P37qhP3.