typeid指针和引用比较的区别?

typeid pointer and reference comparison difference?

当我在摆弄 typeid 时,我注意到了一些奇怪的行为。

#include <iostream>
#include <string>
#include <typeinfo>


int main()
{
    std::cout << "Pointer comparison: " << (typeid(const int*) == typeid(int*))
        << "\nReference comparison: " << (typeid(const int&) == typeid(int&)) << '\n';
}

输出:

Pointer comparison: 0

Reference comparison: 1

在第一种情况下,typeid 正确地表明指向常量值的指针不同于指向非常量值的指针。但是,typeid 似乎表明对常量值的引用与对非常量值的引用相同。

为什么 typeid 给出关于指针和引用的不同结果?

此行为由 C++17 [expr.typeid]/4:

定义

When typeid is applied to a type-id, the result refers to a std::type_info object representing the type of the type-id. If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified referenced type.

也就是说 typeid(const T&)typeid(T&) 都给出与 typeid(T) 相同的结果。

此外,第/5点还涵盖了typeid(T)typeid(const T)相同。对于引用类型和 const/volatile 限定类型,没有单独的 typeinfo 风格。 See cppreference summary.