问题描述
考虑以下代码:
int main() {
const int i = 42;
auto *p = &i; // p is const int *. const is low level const
auto &q = i; // q is const int &. reference to const is always low level
cout << "p = " << typeid(p).name() << endl;
cout << "q = " << typeid(q).name() << endl;
return 0;
}
这是输出:
p = pki
q = i
为什么 typeid(q)
不显示字符 k
表示它是常量
参考? q
是对 const
的引用,并且始终是较低级别。
Why is typeid(q)
not showing the character k
indicating that it's a const
reference? q
is reference to a const
and that is always low level.
推荐答案
在引用的情况下, const
并不是真正的低级(与指针情况相反)。
The const
in case of reference is not really low-level (as opposed to the pointer case).
typeid
应用于表达式 q
的类型。根据以下一般规则,该表达式立即失去其引用类型
typeid
is applied to the type of expression q
. This expression immediately loses its reference type, per the following general rule
5 如果表达式最初的类型为对T的引用(8.3.2,8.5.3),则在进行任何进一步分析之前,将类型调整为T 。表达式指定引用所表示的对象或函数,并且表达式是左值或x值,具体取决于表达式。
5 If an expression initially has the type "reference to T" (8.3.2, 8.5.3), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.
C ++中的表达式永远都没有可见的引用类型,这也意味着 typeid
不能看到引用。在这种情况下,它总是会看到非引用类型的左值或右值。在您的情况下, typeid
将类型为 const int
的左值表达式作为参数。
Expressions in C++ never have visible "reference" types, which also means that typeid
cannot "see" references. It cases like this it always sees lvalues or xvalues of non-reference types. In your case typeid
sees lvalue expression of type const int
as its agument.
其余部分来自 typeid
行为的定义
The rest follows from the definition of typeid
behavior
5.2.8类型识别
5 如果表达式的类型或type-id是cv限定的类型,typeid表达式的结果指向代表cv不限定类型的std :: type_info对象。
5 If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified type.
即 typeid
只是忽略顶级const限定。
I.e. typeid
simply ignores top-level const-qualification.
在指针情况下,您所指的const限定是不是顶级的在 typeid
下不会丢失。
In pointer case the const-qualification you are referring to is a not a top-level one. It is not lost under typeid
.
还要注意 typeid的定义
包含以下规则
其目的是使 typeid
的行为适用于类型名,与上述 typeid
应用于表达式。即应用于typename的 typeed
会忽略引用,也将忽略引用删除后成为顶级的简历质量。
Its purpose is to make the behavior of typeid
applied to typenames consistent with the above behavior of typeid
applied to expressions. I.e. typed
applied to typename ignores references and also ignores cv-quailifications that become top-level after reference removal.
一些额外的例子
typeid(const int) == typeid(int); // <- true
typeid(const int &) == typeid(int); // <- true
typeid(int *) == typeid(int *const); // <- true
typeid(int *) == typeid(const int *); // <- false
这篇关于C ++:typeid忽略了低级const引用,但没有指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!