return 从字符串文字创建的静态 string_view 是否安全?
Is it safe to return a static string_view created from a string literal?
我有一个相对简单的用例:我想将特征与 class 相关联,这将 return 一些用户定义的字符串,即一些用户定义的注册 ID。由于这个注册应该在编译时定义,我希望它是 constexpr 所以我写了如下内容:
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" };
}
};
一切正常,但由于 string_view 实际上并不拥有它的缓冲区,我想知道它是否能保证安全,我指的不仅仅是悬空指针。从我读到的内容来看,字符串文字的生命周期保证与程序本身的生命周期一样长(从这个 SO Lifetime of a string literal returned by a function)。
因此,string_view 的这种用法是否安全且合适?
string literals are guaranteed to have the lifetime as long as that of the program itself
没错。
Therefore, is this usage of string_view
safe and appropriate?
是的,你的代码没问题。
我有一个相对简单的用例:我想将特征与 class 相关联,这将 return 一些用户定义的字符串,即一些用户定义的注册 ID。由于这个注册应该在编译时定义,我希望它是 constexpr 所以我写了如下内容:
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" };
}
};
一切正常,但由于 string_view 实际上并不拥有它的缓冲区,我想知道它是否能保证安全,我指的不仅仅是悬空指针。从我读到的内容来看,字符串文字的生命周期保证与程序本身的生命周期一样长(从这个 SO Lifetime of a string literal returned by a function)。
因此,string_view 的这种用法是否安全且合适?
string literals are guaranteed to have the lifetime as long as that of the program itself
没错。
Therefore, is this usage of
string_view
safe and appropriate?
是的,你的代码没问题。