It is a common mistake to initialize a std::string_view
with a temporary std::string
.
using namespace std::literals;
std::string_view sv1 = "foo" ; // good
std::string_view sv2 = "bar"s; // bad: "foo"s will expire
std::cout << sv1 << "\n" // outputs foo
<< sv2 << "\n"; // undefined behavior
That's because "bar"s
, the temporary std::string
, is destroyed at the end of the full-expression.
But how about "foo"sv
?
std::string_view sv3 = "baz"sv;
Of course this should work, because the suffix sv
is otherwise useless. But how is this fundamentally different from "baz"s
? In other words, why does the string introduced by "baz"sv
not expire?