ev-glaze-constexpr-string-escape-001¶
| 字段 | 值 |
|---|---|
| 项目 | stephenberry/glaze |
| 固定 commit | d78832c82289 |
| 路径 | include/glaze/json/escape_unicode.hpp |
| 行段 | L125-L129 |
| 特性 | constexpr 中的动态分配 |
| 许可证 | MIT |
| 代码来源 | 项目源码 |
| 级别 | manual |
| 审核 | zyuhao7 @ 2026-10-27 |
| 测试代码 | 否 |
| 发现方式 | manual |
用法¶
在 constexpr 函数里构造 std::string 并 reserve 输出长度
为什么典型¶
C++20 允许 constexpr 函数中做瞬态分配,只要在同一个常量求值内释放;序列化库借此在编译期准备转义后的字符串。
摘录¶
// Main function to escape the JSON string.
inline constexpr std::string escape_json_string(const std::string_view input, const size_t output_length)
{
std::string output;
output.reserve(output_length);
备注¶
生产路径;输出长度由单独的 constexpr 计算函数提供,避免运行期重复扩容。