使用constexpr auto / char-array变量观察到不同的行为 [英] Different behavior observed with constexpr auto/char-array variable
问题描述
关注此问题具有constexpr静态string给出链接器错误
在问题中,此代码无法编译:
In the question, this code wasn't able to compile:
#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
版本不会?
My question is why the auto
version works but the array of char
version doesn't?
在允许第二个版本的标准中,并禁止第一个?
Could you please point out the statement in the standard allowing the second version and disallowing the first?
我看了一下与constexpr静态成员变量的奇怪的行为,但似乎是另一个问题。
I took a look at Strange behavior with constexpr static member variable but it seems to be another question.
推荐答案
类中的静态数据成员的声明绝不是定义。
您的示例之间的区别是,只有一个需要定义 text
A declaration of a static data member in class is never a definition.
The difference between your examples is that only one requires a definition of text
.
auto
版本推导 char const * code>,因此
text
只受到左值到右值的转换,而不是odr使用。相比之下,第一个代码有效地传递 text
的地址,odr使用它,即需要一个定义。
The auto
version deduces char const*
, hence text
is only subject to an lvalue-to-rvalue conversion and not odr-used. By contrast, the first code effectively passes text
's address, odr-use-ing it - i.e. necessitating a definition.
这篇关于使用constexpr auto / char-array变量观察到不同的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!