This link states that the second example produces a dangling pointer. How is a dangling pointer created in the second expression but not the first? What is character s after the string?
std::string_view good("a string literal"); // OK: "good" points to a static array
std::string_view bad("a temporary string"s); // "bad" holds a dangling pointer
The
s
constructs a temporarystd::string
from the string literal. Once the execution reaches the semicolon, the temporary is destroyed and a dangling pointer is left in thestd::string
.The
s
there is a user-defined literal operator that produces astd::string
.The difference between the two lines is that the
good
one is astring_view
pointing to a string literal, and string literals have static lifetime (they last for the whole problem). Thebad
one is astring_view
pointing to a temporarystring
, and that temporary owns its data - so when the temporary is destroyed (at the end of the line) it takes its data with it, and we end up withbad
pointing to destroyed memory.