使用 constexpr 自动/字符数组变量观察到不同的行为

Different behavior observed with constexpr auto/char-array variable

本文关键字:观察 变量 自动 constexpr 字符 数组 使用      更新时间:2023-10-16

跟进这个问题 有一个 constexpr 静态字符串会给出链接器错误

在问题中,此代码无法编译:

#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
int main()
{
    std::cout << Test::text << std::endl; // error: undefined reference to `Test::text'
}

从注释中,此代码能够编译:

#include <iostream>
struct Test { static constexpr auto text = "Text"; };
int main()
{
    std::cout << Test::text << std::endl;
}

我的问题是为什么auto版本有效,而char版本数组不起作用?

您能否指出标准中允许第二个版本和不允许第一个版本的声明?

我看了一下 constexpr 静态成员变量的奇怪行为,但这似乎是另一个问题。

类中静态数据成员的声明从来都不是定义。
您的示例之间的区别在于只有一个需要定义text

auto版本推导出char const*,因此text只受制于左值到右值的转换,而不是使用。相比之下,第一个代码有效地传递text的地址,odr-use-ing它 - 即需要一个定义。

struct Test { static constexpr auto text = "Text"; };

解析为

struct Test { static constexpr const char * text = "Text"; };

因此,第二个表达式是指针的constexpr值,而不是数组。