Search code examples
c++returnlifetimelocal-variablesstring-view

How returning a string_view of a local literal works


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


Solution

  • but both g++ and clang say nothing, so this code seems legit and works.

    You cannot deduce latter from the former. A lot of non-legit code produces no warnings.

    That said, string literals have static storage duration, so there is no problem with their lifetime. to_stringview is legit indeed.

    P.S. String literals are arrays of char.

    I was wondering by which mechanism the lifetime of "hello" is different from the lifetime of "hey".

    There is no difference between the lifetime of those two string literals. But "hey"s is not a string literal. It is a "user defined" literal that creates a temporary instance of the class std::string. That temporary object has no static storage duration.