Consider this snippet:
#include <iostream>
#include <string>
#include <string_view>
using namespace std::literals;
class A
{
public:
std::string to_string() const noexcept
{
return "hey"; // "hey"s
}
std::string_view to_stringview() const noexcept
{
return "hello"; // "hello"sv
}
};
int main()
{
A a;
std::cout << "The class says: " << a.to_string() << '\n';
std::cout << "The class says: " << a.to_stringview() << '\n';
}
I was naively expecting some warning in to_stringview()
like returning a reference of a local temporary, but both g++ and clang say nothing, so this code seems legit and works.
Since this generates the expected warning:
const std::string& to_string() const noexcept
{
return "hey"s;
}
I was wondering by which mechanism the lifetime of "hello"
is different from the lifetime of "hey"
.