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?
It is completely safe to use std::string_view in function parameters if the function needs a non-owning view of a string and doesn’t need to store that view somewhere else. Be careful when using std::string_view in return values.
The std::string has some demerits, one of the most common situations is constant strings. Below is the program that demonstrates the problem that occurs in dealing with constant strings with std::string:
Conversion Of std::string_view To C-style String: Functions such as strlen (), these functions need a C-style string in order to be used. So, whenever there is a need to convert a std::string_view to a C-style string, it can be done by first converting to a std::string.
Supports crucial function: The std::string_view supports mostly all crucial function that is applied over the std::string like substr, compare, find, overloaded comparison operators (e.g., ==, <, >, !=). So in most of the cases, it removes the constraint of having a std::string object declaration when our preference is read-only.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With