constexpr 变量和字符串文字
在 C 中,constexpr 变量必须具有文字类型,这意味着它们不能保存具有非平凡析构函数的对象。尝试在 C 11 中定义 constexpr std::string 变量时,由于 std::string 的非平凡析构函数而遇到错误。
constexpr 字符串文字的替代方法
从 C 20 开始,在某些条件下可以在 constexpr 表达式中使用 std::string 。具体来说,std::string 必须在常量求值结束时销毁。
示例:
constexpr std::size_t n = std::string("hello, world").size();
在此示例中,std::string 将作为计算大小的表达式的一部分被销毁,因此代码有效。
String_View替代方案
在 constexpr 表达式中使用类似字符串对象的另一个选项是利用 C 17 中引入的 std::string_view。
示例:
constexpr std::string_view sv = "hello, world";
std::string_view 表示一个不可变、非拥有的类似字符串的对象访问底层字符序列。它没有重要的析构函数,因此适合在 constexpr 表达式中使用。
以上是constexpr 变量可以保存 C 中的字符串吗?的详细内容。更多信息请关注PHP中文网其他相关文章!