標籤:type 運算式 變數 point func vol logs initial sys
C++11 自動推導auto
C++11中引入的auto主要有兩種用途:自動類型推導和傳回值佔位。
auto在C++98中的標識臨時變數的語義,由於使用極少且多餘,在C++11中已被刪除。前後兩個標準的auto,完全是兩個概念。
自動類型推導
auto的自動類型推導,用於從初始設定式中推斷出變數的資料類型。通過auto的自動類型推導,可以大大簡化我們的編程工作。
auto實際上實在編譯時間對變數進行了類型推導,所以不會對程式的運行效率造成不良影響。另外,auto並不會影響編譯速度,因為編譯時間本來也要右側推導然後判斷與左側是否匹配。
#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <vector>#include <map>// 3. 使用模板技術時,如果某個變數的類型依賴於模板參數,不使用auto將很難確定變數的類型template <typename T, typename U>void Multiply(T t, U u){ auto v = t * u; // 使用auto後,將由編譯器自動進行確定}class student{public: static int var1; //auto var2; 錯誤,非靜態成員變數 //static auto var3; 錯誤,需要初始值};int student::var1 = 10;//void fun(auto x = 1) {} 錯誤,auto函數參數,有些編譯器無法通過編譯void mytest(){ //auto a; 錯誤,沒有初始設定式,無法推斷出a的類型 //auto int a1 = 0; 錯誤,auto臨時變數的語義在C++11中已不存在, 這是舊標準的用法。 // 1. 自動協助推導類型 auto a = 10; // a ---> int auto c = ‘A‘; // c ---> char auto s("hello"); // s --> const char * // 2. 類型冗長 std::map<int, std::map<int, int> > map_; std::map<int, std::map<int, int> >::const_iterator itr1 = map_.begin(); const auto itr2 = map_.begin(); auto ptr = []() // ptr ---> void ptr() { std::cout << "mytest ..." << std::endl; }; // lambda 運算式 char x[3]; auto y = x; // y ---> char * // auto會退化成指向數組的指標,除非被聲明為引用 // auto z[3] = x; 錯誤,auto數組,無法通過編譯 return;}int main(){ mytest(); system("pause"); return 0;}
2.使用注意事項
1、我們可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 來修飾auto
auto k = 5;
auto* pK = new auto(k);
auto** ppK = new auto(&k);
const auto n = 6;
2、用auto聲明的變數必須初始化
auto m; // m should be intialized
3、auto不能與其他類型組合連用
auto int p; // 這是舊auto的做法。
4、函數和模板參數不能被聲明為auto
void MyFunction(auto parameter){} // no auto as method argument
template<auto T> // utter nonsense - not allowed
void Fun(T t){}
5、定義在堆上的變數,使用了auto的運算式必須被初始化
int* p = new auto(0); //fine
int* pp = new auto(); // should be initialized
auto x = new auto(); // no intializer
auto* y = new auto(9); // Fine. Here y is a int*
auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)
6、以為auto是一個預留位置,並不是一個他自己的類型,因此不能用於類型轉換或其他一些操作,如sizeof和typeid
int value = 123;
auto x2 = (auto)value; // no casting using auto
auto x3 = static_cast<auto>(value); // same as above
7、定義在一個auto序列的變數必須始終推導成同一類型
auto x1 = 5, x2 = 5.0, x3=‘r‘; // This is too much....we cannot combine like this
8、auto不能自動推導成CV-qualifiers(constant & volatile qualifiers),除非被聲明為參考型別
const int i = 99;
auto j = i; // j is int, rather than const int
j = 100 // Fine. As j is not constant
// Now let us try to have reference
auto& k = i; // Now k is const int&
k = 100; // Error. k is constant
// Similarly with volatile qualifer
9、auto會退化成指向數組的指標,除非被聲明為引用
int a[9];
auto j = a;
cout<<typeid(j).name()<<endl; // This will print int*
auto& k = a;
cout<<typeid(k).name()<<endl; // This will print int [9]
C++11 自動推導auto