c++ - 将 decltype 的表达式从常量左值转换为右值是否也会丢弃 `const`?
问题描述
在这里我想知道类型说明符是如何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
是 justi
而不是const int&
?
解决方案
> 为什么 y 只有 int 类型而不是 const int?
因为(rci + 0)
是纯右值,原始类型的纯右值已被 const 剥离。
> 除了引用运算符 const 限定符之外,将常量左值转换为右值是否也会丢弃?
对于非类类型,const 限定符被丢弃。从标准:
7.3.1.1
[...] 如果 T 是非类类型,则纯右值的类型是 T 的 cv 非限定版本。
> 为什么 typeid 显示 x 的类型只是 i 而不是 const int&?
在所有情况下,typeid 都会忽略 cv 限定符(即 typeid(const T) == typeid(T))。
推荐阅读
- jquery - 使用jquery单击单选按钮时取消选中它本身
- css - 根据 body 类更改 sass 变量
- javascript - 那么如何将数据推送到承诺中的数组?
- wordpress - 我对持久性页面链接有疑问
- aws-api-gateway - Terraform - 如何启用 API Gateway 执行日志记录?
- python - 是否有一种相对可靠的方法来检测当前脚本是否以 PYTHONSTARTUP 运行?
- java - Java 一个用于泊松分布的函数以获得分位数
- c# - C#中的Pramp反句面试题
- google-cloud-platform - 向 GCP 上的数据流作业添加更多工作人员
- ios - Google Maps iOS - 自定义信息窗口按钮不起作用