Search code examples
c++string-view

string append string_view unexpected result


#include <iostream>
std::string_view return_string_view();
using namespace std;
int main()
{
  string got;
  auto peeked = return_string_view();
  got += peeked;
  cout << got << endl;
  return 0;
}
string_view return_string_view()
{
  string const s = string().assign( 2, 'x' );
  auto sv = string_view( s.c_str() );
  return sv;
}

os version

Linux vm 5.19.0-45-generic #46-Ubuntu SMP PREEMPT_DYNAMIC Wed Jun 7 09:08:58 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

gcc version

Linux vm 5.19.0-45-generic #46-Ubuntu SMP PREEMPT_DYNAMIC Wed Jun 7 09:08:58 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

debug info final result

expected return "xx",but why return weird string?


Solution

  • s is destroyed at the end of the scope (when return_string_view returns) so the std::string_view returned by return_string_view is a view over a std::string that has stopped existing.

    Keep in mind that a string_view doesn't own the memory it's a view over. It is typically implemented as a pointer and a length, but the actual data is owned by s.

    Reading from the memory pointed out by the string_view makes the program have undefined behavior. The program could crash, or worse.