This reference states that the second example produces a dangling pointer. How is a dangling pointer created in the second expression but not in the first?
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
Also, what is the character s after the string?
The s there is a user-defined literal operator that produces a std::string.
The difference between the two lines is that the good one is a string_view pointing to a string literal, and string literals have static lifetime (they last for the whole problem). The bad one is a string_view pointing to a temporary string, 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 with bad pointing to destroyed memory.
The s constructs a temporary std::string from the string literal. Once the execution reaches the semicolon, the temporary is destroyed and a dangling pointer is left in the std::string.
The L in front of the string literal creates a wide string. This is usually UTF-16 (Windows) or UTF-32 (Linux).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With