C++11的auto到底萃不萃取cv-qualifier, 实验结果有点矛盾

C++语言 码拜 8年前 (2016-05-11) 1096次浏览
就5行代码:

    const int i = 0;
    auto r1 = i;
    auto& r2 = i;
    r1 = 3;//ok
    r2= 3;//compilation error

第四行编译没有问题,第五行就编译错误了。
为什么呢,auto到底翠不萃取cv-qualifier,还是说对于左值引用才萃取,否则不萃取?
谢谢。

解决方案

5

原来这么高级么,本人的理解就是替换符号…
第二行auto可以换成int, 也可以换成const int, 而可以指定const auto r1 = i指定const int,
但是没法去掉const, 所以第二行是int;
第三行必须是const int, 否则需要const_cast

5

When deducing types for by-value parameters, const and/or volatile arguments are treated as non-const and non-volatile(忽略的是顶层const)
然而引用不会忽略这些的

20

auto 的推断和调用模板函数时对参数的推断一样,由标准 Deducing template arguments from a function call [temp.deduct.call] 约束。
以下 P = auto , A = 初始化表达式

引用

2 If P is not a reference type:
— If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of A for type deduction; otherwise,
— If A is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3) is used in place of A for type deduction; otherwise,
— If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.
3 If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction. If P is an rvalue reference to a cvunqualified template parameter and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction.

假如是 auto 的形式,初始化表达式的顶级 cv 会被忽略
假如是 auto& 的形式,不会做这个转换


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++11的auto到底萃不萃取cv-qualifier, 实验结果有点矛盾
喜欢 (0)
[1034331897@qq.com]
分享 (0)