使用 constexpr 自动/字符数组变量观察到不同的行为
Different behavior observed with constexpr auto/char-array variable
跟进这个问题 有一个 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
值,而不是数组。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 在 make 3.81 中尝试使用重新分配的变量作为依赖项时观察到的奇怪行为
- 观察其值不断变化的变量
- 使用 constexpr 自动/字符数组变量观察到不同的行为
- 如何在c++程序中观察gdb中的变量表
- visual是在c++中访问不从函数外部访问的volatile局部变量的可观察行为
- 如何在Linux中观察变量