Passing string_view when returning string

104 views Asked by At

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?

1

There are 1 answers

3
Daniel Langr On

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 that operator+ returns (by value) a new string object.

If you want to save one allocation, you can modify the std::string_view case as follows:

std::string AddSuffix(std::string_view inputString)
{
  std::string temp;
  temp.reserve(inputString.size() + 1);
  temp = inputString;
  temp += "!";
  return temp;
}

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.