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 @   hacker_dvd  阅读(79)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示