Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a dangling pointer deduced in string_view?

Tags:

c++

c++17

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?

like image 286
bigdata2 Avatar asked May 31 '26 09:05

bigdata2


2 Answers

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.

like image 187
Barry Avatar answered Jun 01 '26 21:06

Barry


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).

like image 27
S.S. Anne Avatar answered Jun 01 '26 23:06

S.S. Anne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!