skip to Main Content
#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?

2

Answers


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

    Login or Signup to reply.
  2. when the return_string_view function returns the string dies and the pointer from s.c_str() doesn’t point to what you expect anymore.

    As @heap-underrun points out, it is noted on cppreference, it is your job to ensure that the pointed to array is still alive. Which it is not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search