为什么自动变量在通过字符串初始化时会被推导为指针?

2023-12-27

#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";
}

Why is x当字符串文字实际上是数组时被推导为指针?

窄字符串文字的类型为“数组”n const char" [2.14.5 字符串文字 [lex.string] §8]


特点auto基于模板参数推导,并且模板参数推导的行为相同,特别是根据 §14.8.2.1/2(C++11 标准):

  • If P is not a reference type
    • 如果 A 是数组类型,则使用数组到指针转换产生的指针类型代替 A 进行类型推导

如果你想要表达式的类型x要成为数组类型,只需添加& after auto:

auto& x = "Hello world!";

然后,auto占位符将被推导为const char[13]。这也类似于将引用作为参数的函数模板。只是为了避免任何混淆: x 的声明类型将是参考- 到数组。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么自动变量在通过字符串初始化时会被推导为指针? 的相关文章

随机推荐