const 与 auto

  1. auto只能推断出类型,引用不是类型,所以auto无法推断出引用,要使用引用只能自己加引用符号

  2. auto关键字在推断引用的类型时:会直接将引用替换为引用指向的对象。其实引用一直是这样的,引用不是对象,任何使用引用的地方都可以直接替换成引用指向的对象

  3. auto关键字在推断类型时,如果没有引用符号,会忽略值类型的const修饰,而保留修饰指向对象的const,典型的就是指针

  4. auto关键字在推断类型时,如果有了引用符号,那么值类型的const和修饰指向对象的const都会保留。

#include <iostream>
#include <boost/type_index.hpp>

int main() {
    using boost::typeindex::type_id_with_cvr;
    int a = 10;
    int b = 20;

    const int* p1 = &a;
    p1 = &b;   // right
    *p1 = 30;  // wrong
    
    int* const p2 = &a;
    p2 = &b;   // wrong
    *p2 = 40;  // right

    auto tp1 = p1;
    tp1 = &b;   // right
    *tp1 = 30;  // wrong

    auto tp2 = p2;
    tp2 = &b;   // right
    *tp2 = 40;  // right

    auto& tp3 = p2;

    const int c = 10;
    auto tc = c;

    // 输出 int const * (等价于 const int *)
    std::cout << type_id_with_cvr<decltype(tp1)>().pretty_name() << std::endl;
    // 输出 int *
    std::cout << type_id_with_cvr<decltype(tp2)>().pretty_name() << std::endl;
    // 输出 int
    std::cout << type_id_with_cvr<decltype(tc)>().pretty_name() << std::endl;
    // 输出 int * const &
    std::cout << type_id_with_cvr<decltype(tp3)>().pretty_name() << std::endl;

    return 0;
}
posted @ 2023-05-08 15:45  hacker_dvd  阅读(96)  评论(0)    收藏  举报