问题描述
在这里,我想知道类型说明符decltype
的工作原理:
const int& rci = 5;// const ref bound to a temporary
decltype (rci) x = 2;
decltype (rci + 0) y = 10;
// ++x; // error: increment of read-only reference ‘x’|
++y; // why does this work
std::cout << typeid(x).name() << std::endl; // i
std::cout << typeid(y).name() << std::endl; // i
-
为什么
y
仅具有类型int
而不是const int
? -
除了引用运算符
const
限定符之外,将常量左值转换为右值也丢弃吗? -
为什么
typeid
显示x
的类型只是i
而不是const int&
?
解决方法
>为什么y仅输入int而不是const int?
因为(rci + 0)
是一个prvalue,并且原始类型的prvalue删除了const。
>将常量左值转换为右值是否还会除引用运算符和const限定符之外也丢弃?
对于非类类型,将删除const限定符。来自standard:
7.3.1.1
[...]如果T是非类类型,则prvalue的类型是T的cv不合格版本。
>为什么typeid显示x的类型只是i,而不是const int&?
来自cppreference:
,在所有情况下,typeid(即typeid(const T)== typeid(T))都会忽略cv限定词。
向int
添加0
(int
是类型const int&
的八进制文字)时得到的表达式的类型是{{1} }。因此int
的类型是y
。
第二点是,在左值到右值转换期间,int
对于非类类型将被丢弃,因为非类类型的右值不能通过cv限定。
最后一点,在所有情况下,const
都会忽略cv限定词。参见https://en.cppreference.com/w/cpp/language/typeid