Creating a string_view
from a temporary is often safe, and it is too useful to disallow.
Recall that the lifetime of a temporary object extends for as long as the full-expression containing it is being evaluated. This is particularly relevant when string_view
is used as a function argument. Consider the case of these two functions:
std::string GetFoo() { /* ... */ }
void SetBar(std::string_view value) {
// code that uses value's contents, possibly copying it into a new
// buffer, but which does not save the string_view for later access
}
Given these functions, it is completely safe to call
SetBar(GetFoo());
because the string_view
representing the temporary string will be valid for the duration of SetBar()
.
string_view
as a parameter type is one of its most important use cases. Its ease of use is directly related to the fact that SetBar()
can be passed any string
or char*
. Disallowing conversion of temporary string
s into string_view
would significantly reduce its usefulness.