#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?
sis destroyed at the end of the scope (whenreturn_string_viewreturns) so thestd::string_viewreturned byreturn_string_viewis a view over astd::stringthat has stopped existing.Keep in mind that a
string_viewdoesn'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_viewmakes the program have undefined behavior. The program could crash, or worse.