1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. std::string_view sv = std::string("temp"); is stored as a…

Added 30 Nov -0001

std::string_view sv = std::string("temp"); is stored as a class member. What is wrong with that?

  1. sv keeps the temporary alive by extending its lifetime, exactly like const& binding
  2. sv refers to a temporary destroyed at the end of the full expression, so it dangles Correct answer
  3. sv owns its own copy of the characters, so the member wastes memory but stays valid
  4. sv is rejected at compile time, because a view cannot bind to a temporary string

Correct answer

B. sv refers to a temporary destroyed at the end of the full expression, so it dangles

17 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs