【C++】auto

auto 的作用

作用:自动类型推导,编译器根据初始化表达式自动推断变量类型,像一些需要类中的迭代器等都可以自动适配类型。

旧 C 语言里auto是「自动存储期」关键字,C++11 起被重新定义成类型占位符。

cpp 复制代码
auto a = 10;        // int
auto b = 3.14;      // double
auto str = "hi";    // const char*
string s = "abc"; // std::string
auto ch = s.begin();

代码对比:

cpp 复制代码
string s = "abc"; // std::string
std::string::iterator it = s.begin();
auto it = s.begin();

重要规则

  1. 必须初始化 ,不能写 auto a;,没有初始值无法推导

  2. 一条声明多个变量,推导出来类型必须相同,否则编译报错

  3. auto会默认丢弃顶层 const

    cpp 复制代码
    const int m = 5;
    auto n = m; // n 是 int,不是 const int
  4. 推导规则等价于模板实参推导

for 的循环用法

cpp 复制代码
vector<int> v{1,2,3};
for(auto val : v){
    cout << val;
}

auto 会对内容进行依次打印出来,原理就是 auto 会调用类里面对应的 begin() 和 end () 迭代器,进行确定为位置,如果类中没有begin 和end 会出现编译错误的情况。

auto 的 const 和 const &

auto 只自动匹配基础类型,不会自动给变量加上引用,也不会默认保留变量的顶层 const;想要引用、只读 const 效果,需要我们自己在 auto 旁边写 & /const。

带引用、const 修饰

cpp 复制代码
int x = 100;
auto &r = x;         // int& 引用
const auto &cr = x;  // const int&
auto *p = &x;        // int*

string 的 auto 的运用

cpp 复制代码
string s = "hello";

// auto:拷贝char,副本修改不影响原字符串
for(auto ch : s)
{
    ch = 'x';
}
cout << s << endl; // hello,原串没变

// auto&:引用字符,可以修改原字符串
for(auto& ch : s)
{
    ch = 'x';
}
cout << s << endl; // xxxxx

// const auto& 只读遍历
const string s2 = "test";
for(const auto& ch : s2)
{
    cout << ch;
}

**注意:**像这种比较大型的类,单纯用auto 会加大拷贝开销,导致运行代码内存时间上的负担,最好能用应用就应用,只读不写的就多加上 const 。

  1. 基础小类型(int、char) auto 拷贝代价很低,写起来简单,只读遍历可以直接 auto;
  2. 大对象(string、自定义类)
  • ✅只读优先:const auto& 避免拷贝
  • 性能最优 ✅需要修改容器元素:auto&
  • ❌不推荐单纯auto,会复制一份大对象,产生额外开销

易错点

cpp 复制代码
vector<string> vec{"A","B"};
for(auto& x : vec){
    x = "new"; // ✅正常修改容器元素
}

const vector<string> cv{"1","2"};
// for(auto& x : cv) {} // ❌报错,普通引用不能绑定const容器的元素
// 出现一个权限放大的情况
for(const auto& x : cv){} // ✅必须const auto&
相关推荐
恋猫de小郭9 小时前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
顧棟9 小时前
组件生命周期设计:从硬编码初始化到状态机
java·ide
特立独行的猫A17 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java18 小时前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
Flynn Liang19 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio20 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易20 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设
文丑颜不良啊20 小时前
LeetCode3041~3060题目解析
java·leetcode
eggwyw20 小时前
C++ union 的一种妙用法
开发语言·c++
文丑颜不良啊1 天前
LeetCode3101~3120题目解析
java·leetcode