std::string_view sv = std::string("temp"); is stored as a class member. What is wrong with that?
Correct answer
B. sv refers to a temporary destroyed at the end of the full expression, so it dangles
17 views
B. sv refers to a temporary destroyed at the end of the full expression, so it dangles
17 views
std::string_view is a non-owning pointer and length pair, so lifetime extension does not apply and a view of a temporary string outlives nothing. Storing such a view in a member leaves a dangling pointer that typically reads freed heap memory. Views are safe for parameters and for data that provably outlives them, such as string literals.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.