简体   繁体   中英

Is it safe to return a static string_view created from a string literal?

I have a relatively simple use case: I want to associate a trait to a class which will return some user defined string, namely some user-defined registration ID. As this registrations are supposed to be defined at compile-time I would like it to be constexpr so I wrote something like the following:

template <typename T>
struct ClassRegistration
{
    static constexpr std::string_view
    Name();
};

template <>                                                                                    
struct ClassRegistration<int>                                                            
{                                                                                              
    static constexpr std::string_view                                                        
    Name()                                                                                     
    {                                                                                          
        return std::string_view{ "int" };                                                     
    }                                                                                          
};

https://godbolt.org/z/5p8xkA

Everything is working fine but as string_view doesn't actually own its buffer I wonder if it's guaranteed to be safe, that I'm not just referring to a dangling pointer. From what I read string literals are guaranteed to have the lifetime as long as that of the program itself (from this SO Lifetime of a string literal returned by a function ).

Therefore, is this usage of string_view safe and appropriate?

string literals are guaranteed to have the lifetime as long as that of the program itself

That's correct.

Therefore, is this usage of string_view safe and appropriate?

Yes, your code is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM