#include <iostream>
#include <typeinfo>
int main()
{
const char a[] = "hello world";
const char * p = "hello world";
auto x = "hello world";
if (typeid(x) == typeid(a))
std::cout << "It's an array!\n";
else if (typeid(x) == typeid(p))
std::cout << "It's a pointer!\n"; // this is printed
else
std::cout << "It's Superman!\n";
}
当字符串字面量实际上是数组时,为什么x
被推断为指针?
一个窄的字符串字面量的类型是"包含n个
const char
元素的数组" [2.14.5 字符串字面量 [lex.string] §8]
auto
和声明类型似乎表明它应该是一个数组,就像你期望的一样。它们清楚地表示它也像模板参数一样解析,这肯定会是一个数组(尽管我刚在GCC中测试了上述模板形式,它也报告为“指针”)。 - edA-qa mort-ora-y