Kenneth
Kenneth

Reputation: 655

string_view return broken in g++ 9.3.0?

In the below code, the string_view value in callee is per design. But after it returns to the caller, it is wrong. The two address are different so it doesn't seem return elision is working. If not, I'd expect at least string_view copy c'tor should work but it doesn't either.

static string_view my_to_string_view(uint32_t value)
{
  std::array<char, 10> str;
  if (auto [ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), value); ec == std::errc())
  {
    cout << "data:" << str.data() << "\n";
    cout << "length is:" << ptr - str.data()<<"\n";
    auto ret = std::string_view(str.data(), ptr - str.data()); // C++17, uses string_view(ptr, length);
    cout << "return value in func:" << ret << "\n";
    return ret;
  }

  throw std::exception();
}

int main()
{
  std::string_view s = my_to_string_view(125);
  std::cout << "return value in main is:"<< s <<"\n";
}

data:125%%�
length is:3
return value in func:125
return value in main is:

Upvotes: 0

Views: 209

Answers (1)

Marshall Clow
Marshall Clow

Reputation: 16690

You're returning a string view that references a local variable. The string_view is fine, but the data it "points to" (i.e, part of the array str) no longer exists.

See CppReference for more information about string_view

Upvotes: 5

Related Questions