跟进这个问题拥有 constexpr 静态字符串会导致链接器错误 https://stackoverflow.com/questions/34792403/having-a-constexpr-static-string-gives-a-linker-error#34792443
在问题中,这段代码无法编译:
#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 静态成员变量的奇怪行为 https://stackoverflow.com/questions/28530583/strange-behavior-with-constexpr-static-member-variable但这似乎是另一个问题。
类中静态数据成员的声明绝不是定义。
您的示例之间的区别在于,只有一个需要定义text
.
The auto
版本推论char const*
, hence text
只进行左值到右值的转换,不使用 ODR。相比之下,第一个代码有效地通过了text
的地址,odr-use-ing它 - 即需要一个定义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)