Reputation: 1041
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?
Upvotes: 3
Views: 639
Reputation: 15586
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).
Upvotes: 3
Reputation: 303337
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.
Upvotes: 6