gpt4 book ai didi

c++ - 为什么 constexpr 没有唯一值或存储空间?

转载 作者:行者123 更新时间:2023-11-28 02:10:59 25 4
gpt4 key购买 nike

我正在使用 Wt::WFormModel,其示例将字段名称表示为 static const char*。我一次对我的项目进行了一系列更改,其中之一是将字段表示更改为 constexpr。经过多次故障排除后,我在 the WFormModel documentation 中找到了这条语句:

The Field type is const char *, and instead of string comparisons to identify fields, pointer comparisons are used. Thus you really should use the same field constant throughout your code to refer to a given field, and you cannot use C++11 constexpr for the field constant since that does not have a unique value (since it has no storage).

constexpr char* 的表示与 const char* 的表示相比如何?

最佳答案

出于同样的原因,这不一定有效:

const char *lit1 = "foo";
const char *lit2 = "foo";
assert(lit1 == lit2);

编译器可以识别出这两个字面值实际上是相同的值,并因此为它们提供相同的存储空间。但它可能不会。而且标准并不要求它。

如果 lit1lit2 在不同的文件中,那么给它们相同的指针值就从编译器技巧变成了链接器技巧。这种情况发生的可能性要小得多。

constexpr 视为一种创建文字的复杂方式。因此,constexpr 变量就像一个文字;它的存储(如果有的话)不受任何一个翻译单元或使用点的约束。编译器/链接器可以将它们全部整理在一起……或者不能。该标准不要求他们这样做。

关于c++ - 为什么 constexpr 没有唯一值或存储空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com