美文网首页
[C++11阅读][3-2-3]auto类型推导(下)

[C++11阅读][3-2-3]auto类型推导(下)

作者: 凌霄阁2010 | 来源:发表于2020-06-29 08:21 被阅读0次

auto搭配指针和引用

auto可化为推导后的类型,如果等号右边是指针,推导出来也带指针,此时auto*和auto没什么区别,例如以下程序的c和d;
但引用会在推导的过程中被“吃掉”,需要手动在auto旁边加上&,例如以下程序的g和h。

int main() {
        int x;
        int * y = &x;
        double foo();
        int & bar();
        auto * a = &x;  // int*
        auto & b = x;  // int
        auto c = y;  // int*
        auto * d = y;  // int*
        auto * e = &foo();  // error: lvalue required as unary ‘&’ operand
        auto & f = foo();  // error: invalid initialization of non-const reference of type ‘double&’ from an rvalue of type ‘double’
        auto g = bar();  // int
        auto & h = bar();  // int&
}

auto与cv限制符关系

cv限制符(cv-qualifier)是指const和volatile,常量的和易失的。
cv限制符可以加在auto的旁边,但推导过程会“吃掉”等号右边的cv限制符,用auto&可以防止等号右边的cv被“吃掉”。

int main() {
    double foo();
    float * bar();
    const auto a = foo();   // const double
    const auto & b = foo(); // const double&
    volatile auto * c = bar();  // volatile float*
    auto d = a; // double
    auto & e = a;   // const double&
    auto f = c; // float*
    volatile auto & g = c;  // volatile float * &
}

auto声明多个变量

和其他变量指示符一样,在一句话中,可以声明多个变量,按第一个变量的推导结果为准,后面几个推导出来的类型必须相同,如果不同就会报编译错误。

int main() {
    auto x = 1, y = 2;
    const auto* m = &x, n = 1;  // OK,auto推导出来用int替代,*是随m的,没有问题
    auto i = 1, j = 3.14f;  // error: inconsistent deduction for ‘auto’: ‘int’ and then ‘float’
    auto o = 1, &p = o, *q = &p;    // OK,从左到右推导
}

总结

有个方法可以比较直观理解auto的规范,标准里称auto是一个将要推导出类型的占位符(placeholder),推导完了拿结果去提到auto的位置。

相关文章

网友评论

      本文标题:[C++11阅读][3-2-3]auto类型推导(下)

      本文链接:https://www.haomeiwen.com/subject/dgekfktx.html