#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
expected return "xx",but why return weird string?
2
Answers
s
is destroyed at the end of the scope (whenreturn_string_view
returns) so thestd::string_view
returned byreturn_string_view
is a view over astd::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 bys
.Reading from the memory pointed out by the
string_view
makes the program have undefined behavior. The program could crash, or worse.when the
return_string_view
function returns the string dies and the pointer froms.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.