从 constexpr 字符串初始化字符数组

Pau*_*aul 2 c++ constexpr

我有类似这样的代码:

#define STR "ABC"
// ...
char s[] = STR;
puts(s);
s[2] = '!';
puts(s);
Run Code Online (Sandbox Code Playgroud)

我尝试用 constexpr 对其进行现代化改造:

constexpr char STR[] = "ABC"
// ...
char s[] = STR;
puts(s);
s[2] = '!';
puts(s);
Run Code Online (Sandbox Code Playgroud)

但它不再编译。

如何从 constexpr 常量初始化堆栈上的字符串而不产生运行时损失?

Qui*_*mby 5

C 样式数组只能由文字初始化,而不能由另一个数组或const char*.

您可以切换到std::array

constexpr std::array<char,4> STR{"ABC"};
int main() {
std::array s{STR};
// OR: auto s{STR};
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它需要指定 中字符串文字的长度STR,如果你有 C++20,你可以使用std::to_array

constexpr std::array STR{std::to_array("ABC")};
Run Code Online (Sandbox Code Playgroud)

可选择替换std::arrayauto.

如果您没有 C++20,您仍然可以使用上面链接中的实现来编写您自己的to_array.

还有std::string_viewandstd::span但两者都是非拥有指针。