c++ auto

 C++11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++98中的标识临时变量的语义,由于使用极少且多余,在C++11中已被删除。前后两个标准的auto,完全是两个概念。

1. 自动类型推断

    auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。
  1. #include <vector>  
  2. #include <map>  
  3.   
  4. using namespace std;  
  5.   
  6. int main(int argc, char *argv[], char *env[])  
  7. {  
  8. //  auto a;                 // 错误,没有初始化表达式,无法推断出a的类型  
  9. //  auto int a = 10;        // 错误,auto临时变量的语义在C++11中已不存在, 这是旧标准的用法。  
  10.   
  11.     // 1. 自动帮助推导类型  
  12.     auto a = 10;  
  13.     auto c = 'A';  
  14.     auto s("hello");  
  15.   
  16.     // 2. 类型冗长  
  17.     map<int, map<int,int> > map_;  
  18.     map<int, map<int,int>>::const_iterator itr1 = map_.begin();  
  19.     const auto itr2 = map_.begin();  
  20.     auto ptr = []()  
  21.     {  
  22.         std::cout << "hello world" << std::endl;  
  23.     };  
  24.   
  25.     return 0;  
  26. };  
  27.   
  28. // 3. 使用模板技术时,如果某个变量的类型依赖于模板参数,  
  29. // 不使用auto将很难确定变量的类型(使用auto后,将由编译器自动进行确定)。  
  30. template <class T, class U>  
  31. void Multiply(T t, U u)  
  32. {  
  33.     auto v = t * u;  
  34. }  

2. 返回值占位

  1. template <typename T1, typename T2>  
  2. auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)  
  3. {  
  4.    return t1+t2;  
  5. }  
  6. auto v = compose(2, 3.14); // v's type is double  

3.使用注意事项

①我们可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 来修饰auto
  1. auto k = 5;  
  2. auto* pK = new auto(k);  
  3. auto** ppK = new auto(&k);  
  4. const auto n = 6;  
②用auto声明的变量必须初始化
  1. auto m; // m should be intialized    
③auto不能与其他类型组合连用
  1. auto int p; // 这是旧auto的做法。  
④函数和模板参数不能被声明为auto
  1. void MyFunction(auto parameter){} // no auto as method argument  
  2.   
  3. template<auto T> // utter nonsense - not allowed  
  4. void Fun(T t){}  
⑤定义在堆上的变量,使用了auto的表达式必须被初始化
  1. int* p = new auto(0); //fine  
  2. int* pp = new auto(); // should be initialized  
  3.    
  4. auto x = new auto(); // Hmmm ... no intializer  
  5.      
  6. auto* y = new auto(9); // Fine. Here y is a int*  
  7. auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)  
⑥以为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid
  1. int value = 123;  
  2. auto x2 = (auto)value; // no casting using auto  
  3.   
  4. auto x3 = static_cast<auto>(value); // same as above   
⑦定义在一个auto序列的变量必须始终推导成同一类型
  1. auto x1 = 5, x2 = 5.0, x3='r';  // This is too much....we cannot combine like this  
⑧auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为引用类型
  1. const int i = 99;  
  2. auto j = i;       // j is int, rather than const int  
  3. j = 100           // Fine. As j is not constant  
  4.   
  5. // Now let us try to have reference  
  6. auto& k = i;      // Now k is const int&  
  7. k = 100;          // Error. k is constant  
  8.   
  9. // Similarly with volatile qualifer  
⑨auto会退化成指向数组的指针,除非被声明为引用
  1. int a[9];  
  2. auto j = a;  
  3. cout<<typeid(j).name()<<endl; // This will print int*  
  4.   
  5. auto& k = a;  
  6. cout<<typeid(k).name()<<endl; // This will print int [9]  
<think>好的,用户想了解C++auto关键字的用法和示例。首先,我需要回忆auto关键字在C++中的发展历史。C++11引入了auto作为类型推导的关键字,允许编译器根据初始化表达式自动推断变量类型。之前的C++标准中,auto用于声明自动存储期的变量,但实际很少使用,因为局部变量默认就是自动存储期。因此,现在的auto用法主要集中在类型推导上。 接下来,需要明确auto的主要用途。根据经验,auto常用于简化复杂类型的声明,比如迭代器、lambda表达式、模板编程中的类型等。此外,用户可能想知道auto的使用场景和注意事项,比如不能用于函数参数、不能推导数组类型等。同时,需要给出具体的代码示例,帮助用户理解如何在实际中使用auto。 然后,检查用户提供的引用内容。引用1提到C++11标准,引用2和3涉及extern关键字和指针的const用法,与auto无直接关联。因此,主要参考引用1中关于C++11的信息,说明autoC++11引入的新特性。 考虑到用户可能需要知道在不同版本中的支持情况,比如C++11及之后的版本。另外,需要提醒用户在使用auto时的最佳实践,比如在类型明显或复杂类型时使用,避免过度使用导致代码可读性下降。 最后,生成相关问题,覆盖用户可能进一步想了解的内容,如类型推导原理、与decltype的区别、在模板中的应用、性能影响等。这些问题应该能帮助用户深入理解auto关键字的不同方面。</think>### C++auto关键字的用法解析 C++11引入的`auto`关键字实现了**自动类型推导**,允许编译器根据初始化表达式推断变量类型。这种机制显著简化了代码书写,尤其在处理复杂类型时效果明显[^1]。 #### 核心用法 1. **基础类型推导** ```cpp auto x = 42; // int auto y = 3.14; // double auto str = "hello"; // const char* ``` 2. **容器迭代器简化** ```cpp std::vector<std::string> names{"Alice", "Bob"}; for(auto it = names.begin(); it != names.end(); ++it) { // it自动推导为std::vector<std::string>::iterator } ``` 3. **lambda表达式存储** ```cpp auto func = [](int a, int b) { return a + b; }; // 推导lambda类型 ``` 4. **模板编程辅助** ```cpp template<typename T, typename U> auto add(T a, U b) -> decltype(a + b) { return a + b; } ``` #### 使用限制 - 不能单独使用(必须初始化):`auto x; // 错误` - 不能推导数组类型:`auto arr = {1,2,3}; // std::initializer_list<int>` - 函数参数中不可用(C++20前) #### 最佳实践场景 1. 迭代器类型冗长时 2. lambda表达式存储时 3. 模板元编程中类型复杂时 4. 提升泛型代码可维护性时 ```cpp // 现代C++典型应用 auto process_data(const auto& container) { // C++20起支持 for(const auto& elem : container) { // 自动类型遍历 // 处理元素... } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值