1

string has a conversion operator to string_view; it constructs a string_view that points into the string's buffer. If this is invoked on a temporary string object, the string_view object will become invalidated due to the dangling pointer very quickly.

Why doesn't string disallow this conversion? It could do so with two conversion operators:

operator string_view() const & { /* ... */ }
operator string_view() && = delete;
Veloso
  • 190
  • 2

1 Answers1

1

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 strings into string_view would significantly reduce its usefulness.

Veloso
  • 190
  • 2
  • 3
    "too useful to disallow" is an unfounded personal position. The conversion should be explicit. Allowing an implicit conversion is as bad as returning a raw pointer. – Richard Hodges Oct 13 '17 at 19:04
  • @RichardHodges: In my opinion, string_view's entire purpose is to make implicit conversions from either char* or std::string, as needed. Requiring explicit object creation ruins the whole point. – Zan Lynx Oct 13 '17 at 19:52
  • 2
    @ZanLynx saving those 8 keystrokes is going to cost a lot of software engineers a lot of hours tracking down random segfaults. I wish you luck. – Richard Hodges Oct 13 '17 at 21:00