constexpr Variables and String Literals
In C , constexpr variables must have a literal type, meaning they cannot hold objects with non-trivial destructors. When attempting to define a constexpr std::string variable in C 11, an error is encountered due to the non-trivial destructor of std::string.
Alternative for constexpr String Literals
As of C 20, it is possible to use std::string in constexpr expressions under certain conditions. Specifically, the std::string must be destroyed by the end of constant evaluation.
Example:
constexpr std::size_t n = std::string("hello, world").size();
In this example, the std::string will be destroyed as part of the expression evaluating the size, so the code is valid.
String_View Alternative
Another option to use string-like objects in constexpr expressions is to utilize std::string_view introduced in C 17.
Example:
constexpr std::string_view sv = "hello, world";
std::string_view represents a string-like object with immutable, non-owning access to an underlying sequence of characters. It does not have a non-trivial destructor, making it suitable for use in constexpr expressions.
The above is the detailed content of Can constexpr Variables Hold Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!