auto 的作用
作用:自动类型推导,编译器根据初始化表达式自动推断变量类型,像一些需要类中的迭代器等都可以自动适配类型。
旧 C 语言里auto是「自动存储期」关键字,C++11 起被重新定义成类型占位符。
auto a = 10; // int auto b = 3.14; // double auto str = "hi"; // const char* string s = "abc"; // std::string auto ch = s.begin();代码对比:
string s = "abc"; // std::string std::string::iterator it = s.begin(); auto it = s.begin();重要规则
- 必须初始化,不能写
auto a;,没有初始值无法推导- 一条声明多个变量,推导出来类型必须相同,否则编译报错
auto会默认丢弃顶层 constconst int m = 5; auto n = m; // n 是 int,不是 const int- 推导规则等价于模板实参推导
for 的循环用法
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 修饰
int x = 100; auto &r = x; // int& 引用 const auto &cr = x; // const int& auto *p = &x; // int*string 的 auto 的运用
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 。
- 基础小类型(int、char)
auto拷贝代价很低,写起来简单,只读遍历可以直接 auto;- 大对象(string、自定义类)
- ✅只读优先:
const auto&避免拷贝- 性能最优 ✅需要修改容器元素:
auto&- ❌不推荐单纯
auto,会复制一份大对象,产生额外开销
易错点
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&