论decltype和auto的区别
decltype和auto的区别
①对引用变量的不同之处:auto将引用变量赋给变量后,变量的类型为引用变量所对应的变量的类型。而decltype则是为引用类型。例子如下:
int i = 0,&r = i;
//same
auto a = i;
decltype (i)b = i;
//different
auto c = r; c为int 类型
decltype (r)d = r;//d为int &类型
②处理底层const的方式不同
auto一般会忽略掉顶层的const,同时底层的const会被保留下来
例子:
const int ci = i,&cr = ci;
auto b = ci;整数
auto c = cr;整数
auto d = &i;整型指针
auto e = &ci;指向整数常量的指针
decltype 则会返回该变量的完整类型(包括顶层const和引用在内)
例子:
const int ci = 0,&cj = ci;
decltype (ci) x = 0;const int 型
decltype (cj) y = x;const int 型
decltype (cj) z ;错误,z是一个引用,引用必须初始化
另外decltype ((variable)) (注意是双层括号)的结果永远是引用,而decltype(variable)结果只有当variable本身是一个引用的时候才是一个引用。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步